/**
 * @author jouyang
 */
var QSLGIN = QS_Lang.Chart,QSLGFD= QS_Lang.Chart,QSLGTXT= QS_Lang.Chart;
var QS_baseChart = {
	  tickerColors:typeof(QS_Style)!="undefined"?QS_Style.chart.tickerColors: ["#728fb2", "#9b0033","#e96610","#f1ad02","#9faa00","#006065","#809aba","#e1b2c1",
		"#e2e5b2","#293f6f","#fbe6b3","#f2a370","#b2cfd0", "#bec5d4","#c5cc66","#f8d1b7","#c36685","#c9cbcb",],//#f1ad02-#7c8577
	  protocol :typeof(QS_PROTOCOL)=="undefined"?(window.location.protocol+"//"):QS_PROTOCOL,
	  drawingData :[{val:"trendline",txt:QSLGTXT.trendline},{val:"rectangle",txt:QSLGTXT.rectangle},{val:"ellipse",txt:QSLGTXT.ellipse},
	       {val:"note",txt:QSLGTXT.note},{val:"levelline",txt:QSLGTXT.levelline},{val:"fibonacci",txt:QSLGTXT.fibonacciretracementlevels}],
	  
	attachMouseScoll:function(){
		var self = this;
		if(this.UIConfig.MouseWheel){
			this.outObj.bind("click.rtqChart",function(e){
				self.scrollAble = true;
			}).bind("mouseout.rtqChart",function(e){
				if (self.scrollAble&&!Util.contains(self.outObj[0], e.relatedTarget)) {// move out chart.
					self.scrollAble = false;
				}
			})
			this.outObj.mousewheel(function(e,d){
				if(!self.scrollAble)return false;
				e.preventDefault();
				if(d>0)self.wheelNum++;
				else self.wheelNum--;
				if(self.mouseWheeTimeout) clearTimeout(self.mouseWheeTimeout);
				self.mouseWheeTimeout = setTimeout(function(){
					self.scrollChart(d>0);
					//console.log(self.wheelNum );
					self.wheelNum = 0;
				},200);
			})
		}
	},
	attachZoomIn:function(){   // attach zoom in and zoom out events to price chart container.
		var self = this, cons = this._contains;
		if(this.UIConfig.ZoomIn){
			cons.pChartContainer.bind("mousedown.rtqChart",this,this._zoomInStart).bind("click.rtqChart",this,this._zoomOutChart).bind(
			"selectstart",function(){
				return false;
			});
		}
	},
	_zoomInStart:function(e){
		var self = e.data;
		if(self.isDrawing){
			return false;
		}
		if(self.selectionMode.zoomIn){
			if(RTQ_ChartUtil.compareDateByday(self.startDate,self.endDate)){
				if(self._frequencyIndexMap[self.frequency]<1){  // xz
				    var cd = self.chartData.DataList;
				    if(!cd.length || !cd[0].data || cd[0].data.length<3) return false;   // only one or two points.
					self.zoomInMode = 1;  // zoom in one day.
				}else{
					return false;  // the date range less than one day.
				}	
			}else{
				self.zoomInMode = 0;
			}
			self._elements.zoomMask.show();
            self._zoomInSize = {};
            self._zoomInSize.s = self._getX(e)-self.chartOffset.left;
            self._elements.zoomMask.css({left:self._zoomInSize.s+"px"});
            $(document).bind('mousemove.rtqChart',self,self._zoomInMove);
            $(document).bind('mouseup.rtqChart',self,self._zoomInStop);

		}else if(self.selectionMode.pan){ // move the chart.
			self._clearZoomIn();
		    self._panSize = {},self._panTimeout = null;
            self._panSize.s = self._getX(e)-self.chartOffset.left;
			self._contains.pChartContainer.addClass("rtc-chart-move");
			$(document).bind('mousemove.rtqChart',self,self._panMove);
            $(document).bind('mouseup.rtqChart',self,self._panStop);
		}
	},
	_zoomInMove:function(e){
		var self = e.data;
		if(self.isDrawing){
			return;
		}
		self._zoomInSize.e = self._getX(e) -self.chartOffset.left;
		var w = self._zoomInSize.e - self._zoomInSize.s;
		if(w<0){
			self._elements.zoomMask.css({width:(w*(-1))+"px",left:(self._zoomInSize.s+w)+"px"});
		}else{
			self._elements.zoomMask.css({width:w+"px"});
		}
		
	},
	_zoomInStop:function(e){
		var self = e.data;
		$(document).unbind('mousemove.rtqChart',self._zoomInMove);
        $(document).unbind('mouseup.rtqChart',self._zoomInStop);
		self._elements.zoomMask.css({width:0,left:0});
		if(!self._zoomInSize.e||!self._zoomInSize.s||Math.abs(self._zoomInSize.e-self._zoomInSize.s)<5) return;
		self._zoomInChart(self._zoomInSize);
	},
	_panMove:function(e){
		if(e.data.isDrawing){
			return false;
		}
		var self = e.data, ep =  self._getX(e)- self.chartOffset.left;
		self._panSize.e = ep<0?0:ep>self.chartWidth?self.chartWidth:ep ;
		var dx = self._panSize.e - self._panSize.s;
		if(Math.abs(dx)<10)return false;  // move less than 10 pixels.
        if(self._panTimeout)clearTimeout(self._panTimeout);
		self._panTimeout = setTimeout(function(){
			 self._moveChart(dx);
		},50);
		//window.getSelection ? window.getSelection().removeAllRanges() : document.selection.empty();//avoid text selecting
	},
	_panStop:function(e){
		var self = e.data;
		self._contains.pChartContainer.removeClass("rtc-chart-move");
	    $(document).unbind('mousemove.rtqChart',self._panMove);
        $(document).unbind('mouseup.rtqChart',self._panStop);
	},
	_getX:function(e){   //
        var self=e.data;
        if(e.pageX)return e.pageX;
        else return e.clientX+document.body.scrollLeft-document.body.clientLeft;
    },
	_moveChart:function(dx){
		if(this.isDrawing){
			return false;
		}
        var w = this.chartWidth - 55, d =  this.chartData.DataList[0].data,md = this.chartData.MiniChartData[0],s,e,sdate,edate;
        var lg = d.length,dTick;
        var dIndx =  Math.abs(Math.floor(lg*dx/w));
        if(dIndx>0){
            if(this._frequencyIndexMap[this.frequency]<1){  // intraday data.
                dTick = d[dIndx][d[dIndx].length-1] - d[0][d[0].length-1];
            }else{ // historical data.
                dTick = (d[dIndx][d[dIndx].length-1] - d[0][d[0].length-1])*86400000;
            }
            if(dTick<86400000)dTick = 86400000; // the minmum of step is one day.
            if(dx>0){// move to left
                var minTick = RTQ_ChartUtil.toDateFromIndex(md[0][md[0].length-1]).getTime();
                if(this.startDate.getTime() == minTick)return false;
                s = new Date(this.startDate.getTime() - dTick);
                e = new Date(this.endDate.getTime() - dTick);
                var dx = 0;
                if(s.getDay()==0){
                    dx = 2;
                    s = new Date(this.startDate.getTime() - (dTick+dx*86400000));
                }else if(s.getDay()==6){  //weekend day
                    dx = 1;
                    s = new Date(this.startDate.getTime() - (dTick+dx*86400000));
                }
                if (e.getDay() == 0) {
                    e = new Date(this.endDate.getTime() - (dTick + 2 * 86400000));
                }else if (e.getDay() == 6) {
                    e = new Date(this.endDate.getTime() - (dTick + 86400000));
                }
                if(s.getTime()<minTick){  // out of left range. 
                    s = new Date(minTick);
                }
                this.startDate = s, this.endDate = e;
				//console.log(s+"|"+e);
                this.changeRange(11);
            }else{ // move to right.
                if(!RTQ_ChartUtil.compareDateByday(this.endDate,this.latestTradeDate)){
                    s = new Date(this.startDate.getTime() + dTick);
                    e = new Date(this.endDate.getTime() + dTick);
                    var dx = 0;
                    if(s.getDay()==0){
                        dx = 1;
                        s = new Date(this.startDate.getTime() + (dTick+dx*86400000));
                    }else if(s.getDay()==6){  //weekend day
                        dx = 2;
                        s = new Date(this.startDate.getTime() + (dTick+dx*86400000));
                    }
                   if (e.getDay() == 0) {
                        e = new Date(this.endDate.getTime() + (dTick + 86400000));
                    }else if (e.getDay() == 6) {
                        e = new Date(this.endDate.getTime() + (dTick + 2*86400000));
                    }
                    if((e.getTime()-this.latestTradeDate.getTime())>0){  // move out of range.
                        e = this.latestTradeDate;
                    }
                    this.startDate = s, this.endDate = e;
					//console.log(s+"|"+e);
                    this.changeRange(11);
                }       
            }
            this._panSize.s = this._panSize.e;
        }
    },
	_zoomInChart:function(zoomIn){  // zoom in chart by custom date.
		var w = this.chartWidth - 55, d =  this.chartData.DataList[0].data,s,e,sdate,edate;
		var lg = d.length;
		s=zoomIn.s>zoomIn.e?zoomIn.e:zoomIn.s, e = zoomIn.s<zoomIn.e?zoomIn.e:zoomIn.s;
		if(this.yaxisAlign=="left"){
            s=s-55, e=e-55;
        }
		if(s<0)s = 0;
		if(e>w)e = w;
		var sIndex = Math.floor(lg*s/w), eIndex = Math.floor(lg*e/w),eDx = lg-eIndex;
		if(sIndex<0)sIndex=0;
		if(eIndex>=lg)eIndex = lg-1;
		if(lg<1)return false;
		if(this.zoomInMode == 0){
			var sdIn = d[sIndex][d[sIndex].length-1],edIn=d[eIndex][d[eIndex].length-1];
		    sdate = this._frequencyIndexMap[this.frequency]<1? new Date(sdIn):RTQ_ChartUtil.toDateFromIndex(sdIn);
		    edate = this._frequencyIndexMap[this.frequency]<1? new Date(edIn):RTQ_ChartUtil.toDateFromIndex(edIn);
		    //console.log(sdIn+"|"+this.frequency);console.log(edIn+"|"+this.frequency);
		    if(!RTQ_ChartUtil.compareDateByday(sdate,this.startDate)||!RTQ_ChartUtil.compareDateByday(edate,this.endDate)){  // change the date range.
		        if(this.zoomStack)this.zoomStack.push({s:this.startDate,e:this.endDate}); // push in last state;
		        this.startDate= sdate;
		        this.endDate =  edate;
		        this.changeRange(11);
		    }
		}else if(this.zoomInMode == 1){  // zoom in one day.
			//this.freshAllCharts();
		    var d = this.chartData;
			this._zoomInData(sIndex,eIndex,d.DataList);
			if(this.zoomStack)this.zoomStack.push({s:this.startDate,e:this.endDate}); // push in last state;
			this.drawPChart();
			if(d.VolList&&d.VolList.length){
				this._zoomInData(sIndex,eIndex,d.VolList);
				this.drawVChart();
			}
			var ida = this.iChartData;
			for(var o in this.iChartData){
				if(this.iChartData[o]&&this.iChartData[o].length){
					this._zoomInData(sIndex,eIndex,this.iChartData[o]);
					this.drawIChart(o);
				}
			}
			if(this.zoomIndexRange==null){
				this.zoomIndexRange = {s:sIndex,e:eIndex};
			}else{
				this.zoomIndexRange.s+=sIndex, this.zoomIndexRange.e-=eDx;
			}
			//this.zoomInMode = -1;
			
		}
		
		//console.log(this.startDate+"|"+this.endDate);
	},
	_zoomInData:function(sIndex,eIndex,dataList){
		if(!dataList||!dataList.length)return;
		for(var i= 0;i<dataList.length;i++){
			if(dataList[i].name=="VBP") {
                dataList.splice(i,1);
                i--;
                continue;
            }
			this._zoomInDataItem(sIndex,eIndex,dataList[i]);
        }   
	},
	_zoomInDataItem:function(sIndex,eIndex,dataItem){
        var lg = dataItem.data.length;
        dataItem.data.splice(0,sIndex);
        dataItem.data.splice(eIndex-sIndex,lg-eIndex);
        for(var j=0;j<dataItem.data.length;j++){
            dataItem.data[j][0]=j;
        }
	},
	_clearZoomIn:function(){
		if(this.zoomStack)this.zoomStack = []; 
		this.zoomInMode = -1;
		this.zoomIndexRange = null;
	},
	_changeZoomInIndex:function(oldFre,fre){
		if(!this.zoomIndexRange)return;
		var rate = this._frequencyMap[oldFre]/this._frequencyMap[fre];
		if(!isNaN(rate)){
			this.zoomIndexRange.s=Math.ceil(this.zoomIndexRange.s*rate);
            this.zoomIndexRange.e=Math.ceil(this.zoomIndexRange.e*rate);
		}
		
	},
	_zoomOutChart:function(e){
		var self = e.data;
		if(self.selectionMode.zoomOut&&self.zoomStack&&self.zoomStack.length){
			var dates = self.zoomStack.pop();
            self.startDate = dates.s, self.endDate = dates.e;
            self.changeRange(11);
		}
	},
	_resetZoomChart:function(){
		var self = this;
		if(self.selectionMode.reset&&self.zoomStack&&self.zoomStack.length){
			var dates = self.zoomStack[0];
			self._clearZoomIn();
            self.startDate = dates.s, self.endDate = dates.e;
            self.changeRange(11);
		}
	},
	_zoomChart:function(f,isZoomIn,dx){  // when mouse wheel zoom the chart.
	    this._clearZoomIn(); 
		if (isZoomIn) {
            if (this.startDate.getTime() > this.sDates[f].getTime()) {
                this.startDate = new Date(this.startDate.getFullYear(), this.startDate.getMonth(), this.startDate.getDate() - Math.abs(this.wheelNum)*dx);
                this.changeRange(11); 
            }
        }else {
            if (this.startDate.getTime() < this.endDate.getTime()) {
                var s = new Date(this.startDate.getFullYear(), this.startDate.getMonth(), this.startDate.getDate() + Math.abs(this.wheelNum)*dx);
                if(s.getTime()>this.endDate.getTime()){
                    this.startDate = this.endDate;
                }else{
                    this.startDate = s;
                }
                this.changeRange(11); 
            }
        }
	},
	scrollChart:function(isZoomIn){
		if(this._frequencyIndexMap[this.frequency]==-4){
			this._zoomChart("lMin",isZoomIn,1);
		}else if(this._frequencyIndexMap[this.frequency]>=-3&&this._frequencyIndexMap[this.frequency]<1){
			this._zoomChart("lMin",isZoomIn,2);
		}else if(this._frequencyIndexMap[this.frequency]==1){
			this._zoomChart("d",isZoomIn,20);
		}else if(this._frequencyIndexMap[this.frequency]==2){
			this._zoomChart("w",isZoomIn,42);
		}else if(this._frequencyIndexMap[this.frequency]==3){
			this._zoomChart("m",isZoomIn,120);
		}	
	},
	_createIndicatorInputWin: function(container){  // create a input window for indicators' parameters.
		container.append('<div class="rtc-win qs-chart-indicator-prompt" style="display:none">'+
			'<div class="rtc-win-wrap" ><div class="rtc-win-title qs-chart-indicator-prompt-title">'+
			'<strong class = "qs-ind-title"></strong> <a class="qs-chart-indicator-prompt-close"></a>'+
			'</div> <div class="rtc-win-content"></div><div class="rtc-win-action">'+
			'<a href="javascript:void(0)" class="qs-ui-btn ok qs-ind-draw">&nbsp;'+QSLGTXT.draw+'&nbsp;</a>'+
			'<a href="javascript:void(0)" class="qs-ui-btn qs-ind-cancel">'+QSLGTXT.cancel+'</a> <a href="javascript:void(0)" class="qs-ui-btn qs-ind-remove">'+QSLGTXT.remove+'</a>'+
			' </div> </div> </div>');
		var el = this._elements, self = this;
		el.indicatorWinElm = container.find(".rtc-win");
		el.indicatorWinElm.find(".qs-ind-draw").unbind("click").bind("click",function(){
				if(self.ichartSiwtchIndicatorWin.flag){
					self.preSwitchIChart()
				}
				self._drawIndicator(self._selectedIndicatorName);
			}
		);
        el.indicatorWinElm.find(".qs-ind-cancel").unbind("click").bind("click",function(){self.cancelIndicator();}); 
        el.indicatorWinElm.find(".qs-ind-remove").unbind("click").bind("click",function(){self.removeIndicatorClicked();});
        el.indicatorWinElm.find(".qs-chart-indicator-prompt-close").unbind("click").bind("click",function(){self.cancelIndicator();});   
	},
	_createDateInputBoxes:function(){
		var uiComps = this.uiComponents, uc = this.UIConfig,el = this._elements,self = this,hcolor="#FEFEFE";		
		var bindEvent = true, w = 72;
		if(uc.chartCtrl == "rtqPanel"){
			bindEvent = false;
		} 
		uiComps.customDateB = new RTQ_chartCustomDataBox(el.$customDate,{
			startDate:self.startDate,
			endDate:self.endDate,
			width:w,
			splitLabel:"-",
			hoverColor:hcolor,
			callback:function(s,e){
				self.startDate = s, self.endDate = e;
				self._clearZoomIn(); 
				self.changeRange(11);
			},
			bindEvent:bindEvent
		});
		if(!bindEvent){ //setting panel add calendler control.
			var calInputs = el.$customDate.find(".qs-ui-ipt");
			uiComps.customDateB.inputBoxes.attr("readOnly","true");
			calInputs.each(function(i){
				$(this).data("cal.Index",i);
			});
			QSCAL.register(calInputs[0],function(date){
                if(date.getTime()>self.endDate.getTime()){
                    self.startDate=self.endDate;
					self.endDate = date;
                    calInputs.eq(1).val(RTQ_ChartUtil.formatMDYDate(self.endDate));
                }else{
					self.startDate=date;
				}
                calInputs.eq(0).val(RTQ_ChartUtil.formatMDYDate(self.startDate));
                self._clearZoomIn();
                self.changeRange(11);
            });
            QSCAL.register(calInputs[1],function(date){
                if(date.getTime()<self.startDate.getTime()){
                    self.endDate = self.startDate;
					self.startDate = date;
                    calInputs.eq(0).val(RTQ_ChartUtil.formatMDYDate(self.startDate));
                }else{
					self.endDate = date;
				}
                calInputs.eq(1).val(RTQ_ChartUtil.formatMDYDate(self.endDate));
                self._clearZoomIn();
                self.changeRange(11);
            });
			calInputs.focus(function(e){
				var target=$(e.target),index = target.data("cal.Index");
				if ($.browser.msie) {       // fixed the issue that hit backspace key will back the web page.
					document.body.focus();
				}
				if (index==0) {
					QSCAL.show(target,self.startDate);
				}else{
					QSCAL.show(target,self.endDate);
				}		
			});
		}	
	},
	_createIChartRightMenu: function(){  // create mini-chart right menus.
		var inx = 0;
		if(typeof(this.indicatorPanelData)!="undefined"&&this.indicatorPanelData.length){
			for(var i = 1;i<this.indicatorPanelData.length;i++){
				var k = this.indicatorPanelData[i],t=[];
				for(var j = 0;j<k.length;j++){
					if(this.indicatorsData[k[j].val]&&this.indicatorsData[k[j].val].type==1){
						t.push($.extend(true,{},k[j],{idx:inx+1}));
					}
				}
				this.ichartMenuL1Data[inx++]=t;
				//this.ichartMenuData.push(t);
			}
		}
		if (typeof(this.fundamentalPanelData) != "undefined" && this.fundamentalPanelData.length) {
			for (var i = 0; i < this.fundamentalPanelData.length; i++) {
				var k = this.fundamentalPanelData[i], t = [];
				for (var j = 0; j < k.length; j++) {
					if (k[j].val != "FairValue") {
						t.push($.extend(true, {}, k[j], {
							idx: inx + 1
						}));
					}
				}
				
				this.ichartMenuL1Data[inx++] = t;
				//this.ichartMenuData.push(t);
			}
		}
		var  j = 0;
		for(var i = 0; i<this.miniChartRightMenuData.length;i++){
			if(this.miniChartRightMenuData[i].hasSubMenu&&j<this.ichartMenuL1Data.length){
				this.miniChartRightMenuData[i].subMenu = this.ichartMenuL1Data[j];
				j++;
			}
		}
        if (typeof(Util.CascadeMenu) == "function") {
            var self = this, uiComp = this.uiComponents, el = this._elements;
            uiComp.miniChartRightMenu.menu = new Util.CascadeMenu((this.__winObj && this.__winObj.toolPanel ? this.__winObj.toolPanel : this.outObj), {
                display: false,
                autoHide: true,
                isTraceMouse: true,
                fixedDirection: false
            }, this.miniChartRightMenuData, {
                onClick: function(data){
                    var idx = data.data.idx;
                    self._onIchartMenuItemClicked(idx, data);
                }
            });
        }
	},
	_getCommonConfig:function(){
		var cfg ={autoTitle:this.autoTitle,pWidth:this.chartWidth,pHeight:this.pChartHeight,chartStyle:this.chartStyle,chartCursor:this.chartCursor,scaleType:this.scaleType,lock:this.lock,showNotes:this.showNotes,yaxisAlign:this.yaxisAlign,isShowTimeSlider:this.isShowTimeSlider};
		var inds = {},vals={},indD = this.indicatorsData;
		for(var o in indD){
			if(indD[o].show){ // volume: default value is true.
				if(o == "SMA"||o == "SMAV"||o == "EMA"){
					inds[o]= {show:true,num:typeof(indD[o].num)=="object"?$.extend(true,[],indD[o].num):indD[o].num};
				}else{
					inds[o]= {show:indD[o].show,parameter:$.extend(true,[],indD[o].parameter)};
				}
			}
		}
		for(var o in this.valuations){
			if(this.valuations[o].show){
				vals[o]= {show:true};
			}
		}
		cfg.indicatorsData=inds;
		cfg.valuations=vals;
		return cfg;
	},
	_createRightMenu: function(container){
        var self = this, uiComps = this.uiComponents, el = this._elements;
        this.uiComponents.rightMenu = new Util.CascadeMenu((this.__winObj && this.__winObj.toolPanel ? this.__winObj.toolPanel : this.outObj), {
            display: false,
            autoHide: true,
            isTraceMouse: true,
            fixedDirection: false
        }, this.rightMenuData, {
            onClick: function(data){
                if (data != null) {
                    if (data.parent != null && data.parent.data.catekey == "zoom") { // combined menu
                        var oldFre = self.frequency, ss = "";
						self.frequency = data.data.val;
                        if (data.data.val != self.frequency) {
							if(self.zoomInMode==1){ // zoom in one day.
							    if(self._frequencyIndexMap[self.frequency]>0){
									self._clearZoomIn(); 
								}else{
									self._changeZoomInIndex(oldFre,self.frequency); 
								}   
				            }
                        }
                        var zVal = parseInt(data.parent.data.val, 10);
                        if (self.zoomRange != zVal) { // change zoom type;
                            if (uiComps.ddlZoom != null) { // change the dropdownlist UI state
                                uiComps.ddlZoom.setTextValue("", zVal);
                            }
                            self.uiComponents.rightMenu.changeUIState(oldFre, self.zoomRange, false); // chang
                            self.uiComponents.rightMenu.changeUIState(zVal, "zoom", true);
                            ss = self.zoomListData[self._zoomIndexMap[zVal]].txt + " | " + self._frequencyTxtMap[self.frequency];
                            el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(ss);
                            self.changeRange(zVal);
							self._clearZoomIn(); 
                        } else { //only change frequency
                            if (uiComps.ddlFrequency != null) {
                                uiComps.ddlFrequency.setTextValue("", self.frequency);
                            }
                            if (uiComps.tabZoomMenu != null) {
                                uiComps.tabZoomMenu.changeUIState(self.frequency, self.zoomRange, true);
                                ss = self.zoomListData[self._zoomIndexMap[zVal]].txt + " | " + self._frequencyTxtMap[self.frequency];
                                el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(ss);
                            }
                            self.drawChartSegment();
                        }
                    } else {
                        var cateKey = data.parent == null ? null : data.parent.data.val;
                        var val = data.data.val, checked = data.checked ? true : false;
                        self._onMenuItemCallback(cateKey, val, checked);
						if(cateKey=="zoom"&&val==11){  
                            if(self.__winObj&&self.__winObj.settingPN){
                                self.__winObj.settingPN.show();
                            }
                        }
                    }
                }
                self.uiComponents.rightMenu.hide();
            }
        });
        container.unbind("contextmenu").bind("contextmenu", function(e){
            self.uiComponents.rightMenu.show(e);
            self._elements.crosshairLegendWin.hide();
            self._elements.lineXElm.hide();
            self._elements.lineYElm.hide();
            e.preventDefault();
        });
	},
	_createTabMenu:function(){  // create tab menu and zoom menu in tab menu.
		var uiComps = this.uiComponents, self = this, el = this._elements;
		var tabEl = $('.rtc-tab',this.outObj);
	    uiComps.tabMenu = new Util.TabMenu(tabEl[0],this.tabList, {
        onActive: function(tab){
			var inx = tab.index, v = self.tabMap[inx];              
			uiComps.ddlChartType.selectItemByValue(v);
        }
        },{ width:80,
           isExcuteCallbackAtInit:false
        });	
		for(var i = 0;i<this.chartTypeMenuData.length;i++){
			var tarr = this.chartTypeMenuData[i];
			if(tarr.length>0){
                var tabItem = uiComps.tabMenu.getTabById(i); // growth tab;
                var ii = i;
                (function(){
					var i = ii;
                    uiComps.chartTypeMenu[i] = new Util.CascadeMenu(tabEl, {
                        display: false,
                        isTraceMouse: false,
                        autoHide: true
                    }, tarr, {
                        onClick: function(data){
                            var d = data.data;
                            var v = d.val;
                            if (uiComps.ddlChartType != null) {
                                uiComps.ddlChartType.selectItemByValue(v);
                            }
                            uiComps.chartTypeMenu[i].hide();
                        }
                    });
                    tabItem.menu.hover(function(e){
                        var p = $(this).position();
                        uiComps.chartTypeMenu[i].setPosition(p.left, p.top + 23);
                        uiComps.chartTypeMenu[i].show();
                    }, function(e){
                        uiComps.chartTypeMenu[i].hide();
                    });
				})()
			}
		}
		uiComps.tabZoomMenu = new Util.CascadeMenu(el.tabmenuZoomEl,{display:false,isTraceMouse:false,autoHide:false,fixedDirection:true},
			this.zoomListData,
			{
                onClick: function(data){
                    var d = data.data, v = d.val, oldFre = self.frequency, ss;
                    if (data.parent != null && v != self.frequency) { // not custom button
                        if(self.zoomInMode==1){ // zoom in one day.
	                        if(self._frequencyIndexMap[v]>0){
	                            self._clearZoomIn(); 
	                        }else{
	                            self._changeZoomInIndex(self.frequency,v); 
	                        }   
	                    }
						self.frequency = v;
                    }
                    var zVal = parseInt(data.parent == null ? data.data.val : data.parent.data.val);// custom button.
                    if (self.zoomRange != zVal) { // change zoom type;
                        if (uiComps.ddlZoom != null) { // change the dropdownlist UI state
                            uiComps.ddlZoom.setTextValue("", zVal);
                        }
                        uiComps.tabZoomMenu.changeUIState(oldFre, self.zoomRange, false); // chang
                        uiComps.tabZoomMenu.changeUIState(zVal, null, true);
                        if (uiComps.rightMenu != null) {
                            uiComps.rightMenu.changeUIState(oldFre, self.zoomRange, false); // chang
                            uiComps.rightMenu.changeUIState(zVal, "zoom", true);
                        }
                        ss = self.zoomListData[self._zoomIndexMap[zVal]].txt + " | " + self._frequencyTxtMap[self.frequency];
                        el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(ss);
						self._clearZoomIn();  // clear the zoom in stack;
                        self.changeRange(zVal);
                    } else if (data.parent != null) { //only change frequency not contains custom button
                        if (uiComps.ddlFrequency != null) {
                            uiComps.ddlFrequency.setTextValue("", self.frequency);
                        }
                        if (uiComps.rightMenu != null) {
                            uiComps.rightMenu.changeUIState(self.frequency, self.zoomRange, true);
                        }
                        ss = self.zoomListData[self._zoomIndexMap[zVal]].txt + " | " + self._frequencyTxtMap[self.frequency];
                        el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(ss);
                        self.drawChartSegment();
                    }
                    uiComps.tabZoomMenu.hide();
				   
                }
			});
		el.tabmenuZoomEl.hover(function(e){
			uiComps.tabZoomMenu.show();
		},function(e){
			uiComps.tabZoomMenu.hide();
		})
	},
	menuButtonClicked: function(obj)  {              // menu item clicked
    	var el = $(obj), catKey = el.attr("catkey"),va = el.attr("value"),checked = el.hasClass("rtq-chkbox_off");
       	this._onMenuItemCallback(catKey,va,checked);
    },
	_onMenuItemCallback:function(catKey,va,checked){
		var uiComp = this.uiComponents, el = this._elements;
		if (catKey == "chartType" && uiComp.ddlChartType != null) {
            uiComp.ddlChartType.selectItemByValue(va);
            return false; 
        } else if (catKey == "frequency" && uiComp.ddlFrequency != null) { // change frequency
            uiComp.ddlFrequency.selectItemByValue(va);
            return false;
        } else if(catKey == "cursorType" && uiComp.ddlCursorType != null) {
            uiComp.ddlCursorType.selectItemByValue(va);
            return false;
        } else if (catKey == "zoom") {
            uiComp.ddlZoom.selectItemByValue(va);
            return false;
        }else if(catKey == "scale"){
			this.ratioScaleSelected(va);
            return false;
		}else if(catKey == "yaxis"){
			this.ratioYaxisSelected(va);
            return false;
		}else if(catKey == "selectionmode"){
			this.ratioSelectionModeSelected(va);
            return false;
		}else if(catKey=="draw"){
			var ckd = el.$drawBlock.find("[value='"+va+"']").hasClass("draw-row-select");
			el.$drawBlock.find(".draw-row-select").removeClass("draw-row-select");
			if(!ckd){
				el.$drawBlock.find("[value='"+va+"']").addClass("draw-row-select");
				for(var i = 0;i<this.drawingData.length;i++){
					if(va == this.drawingData[i].val){
						this.beginDrawing(va);
						break;
					}
				}
			}else{
				this.cancelDrawing(va);
			}
		} else if (catKey == "event") {
            if (uiComp.rightMenu != null) { 
                uiComp.rightMenu.changeUIState(va,null,checked);
            }
			if(checked){
				el.eventULElm.find("a[value='"+va+"']").removeClass("rtq-chkbox_off");
			}else{
				el.eventULElm.find("a[value='"+va+"']").addClass("rtq-chkbox_off");
			}
			this.events[va]= checked;
            if(this.zoomRange > 2) {
                this.getPChartData();
            }      
        } else if (catKey == "indicator") { 
            this.showIndicatorWin(va);       
        } else if(catKey == "indexs"){
			if(this.compairTickers.length >= this.tickerMaxNum && checked){
				if (this.hasConfirmBox) {
                    Util.message(TEXT?TEXT.ChartCTickersOverstep:"The maximum compair tickers are reached.");
				}
				return false;
			}
			this.indexsMap[va].show = checked;
			el.indexsULElm.find("a[value='"+va+"']").toggleClass("rtq-chkbox_off");
            //el.indexsULElm.find("a[value='"+va+"']")[checked?'addClass':'removeClass']("rtq-chkbox_off"); //david
			if(this.indexsMap[va].show){
				this.addCompairTickers(va);
			} else {
				this.removeCompairTicker(va);
			}
		} else if(catKey == "relateSec"){
			if(this.compairTickers.length >= this.tickerMaxNum&&checked){
				if (this.hasConfirmBox) {
                    Util.message(TEXT?TEXT.ChartCTickersOverstep:"The maximum compair tickers are reached.");
                }
				return false;
			}
			el.relatedSecULElm.find("a[value='"+va+"']").toggleClass("rtq-chkbox_off");
            //el.relatedSecULElm.find("a[value='"+va+"']")[checked?'addClass':'removeClass']("rtq-chkbox_off"); //david
			if(checked){
				this.addCompairTickers(va);
			} else {
				this.removeCompairTicker(va);
			}
		}else if (catKey == "valuation"||catKey == "mainl1-fundamental"||catKey=="mainl1-valuation"){ // draw valuation chart.
			el.valuationULElm.find("a[value='"+va+"']").toggleClass("rtq-chkbox_off");
			if(this.valuations[va]){
				var isShow = false;
				if(!this.valuations[va].show){
					this.addValuations(va);
					isShow = true;
				}else {  
					this.removeValuations(va);
				}
				this.changeRightMenuClass(2,va,isShow);
			}
		}else if(catKey.indexOf("mainl2-")==0){
			this.showIndicatorWin(va); 
		}
	},
	getIChartsHeight:function(){
		var ih = 0;
		if(typeof(this.indicatorsData)!="undefined"){
			for (var o in this.indicatorsData) { 
	            if (this.indicatorsData[o].show && this.indicatorsData[o].type == 1) {
	                ih += this.iChartHeight;
	            }   
	        }
		}
		if(typeof(this.valuations)!="undefined"){
			for (var o in this.valuations) { 
	            if (this.valuations[o].show && o!="FairValue") {  // Fair Value is overlay chart.
	                ih += this.iChartHeight;
	            }   
        	}
		}
        return ih;
	},
	setSize:function(wd,hg) { 
		var cons = this._contains; 
       	this._setSizeParas(wd,hg);
        this.outObj.css({width:this.chartWidth+"px",height:this.outHeight+"px"});
        if(cons.pChartContainer)cons.pChartContainer.css({width:this.chartWidth+"px", height:this.pChartHeight+"px", "float":"left"});
        if(cons.vChartContainer)cons.vChartContainer.css({width:this.chartWidth+"px", height:this.vChartHeight+"px", "float":"left"});
        if(cons.mChartContainer)cons.mChartContainer.css({width:this.chartWidth+"px", height:this.miniChartHeight, "float":"left"});
		if(this._elements.zoomMask!=null)this._elements.zoomMask.css({height:this.pChartHeight+"px"});
        this.outObj.find(".rtc-chart-container").find(".rtc-chart").css({width:this.chartWidth+"px"});
    },
	changeOutSize: function(wd,hg) {  
        this.outHeight = hg;
        var wid =  wd <  this.minW? this.minW:wd;
        this.setSize(wid,hg);
        if(typeof(this.pFlot)!="undefined"&&this.pFlot != null) {
            this.pFlot.changeOutSize(this.chartWidth,this.pChartHeight);
        }
        if(typeof(this.vFlot)!="undefined"&&this.vFlot != null && this.showVolume) {
            this.vFlot.changeOutSize(this.chartWidth,this.vChartHeight);
        }
        if(typeof(this.mFlot)!="undefined"&&this.mFlot != null && this.isShowTimeSlider) {
            this.mFlot.changeOutSize(this.chartWidth,this.miniChartHeight);
            if(this.sliderObj != null ) {
                this.sliderObj.changeOutSize(this.chartWidth,this.miniChartHeight);
            }
        }
		for(var o in this.iFlots){
			if(this.iFlots[o]!=null && ((this.valuations&&this.valuations[o]&& this.valuations[o].show)||(this.indicatorsData[o]&&this.indicatorsData[o].show))){
				this.iFlots[o].changeOutSize(this.chartWidth,this.iChartHeight-20); // reduce the  heigth of chart legend.
			}
		}
    },
	// dropdown list callbacks.
	zoomSelected:function(t,v) {
		this._clearZoomIn(); 
        this.changeRange(parseInt(v));
		this.uiComponents.ddlZoom.setTextValue("",v);
        return false;
    },
	frequencySelected:function(k,v){
		var el = this._elements, uiComp = this.uiComponents;
        if (this.frequency != v) { 
            if (uiComp.rightMenu != null) { 
				uiComp.rightMenu.changeUIState(v,this.zoomRange,true);
            }
			if(uiComp.tabZoomMenu!=null){
				uiComp.tabZoomMenu.changeUIState(v,this.zoomRange,true);
				var ss = this.zoomListData[this._zoomIndexMap[this.zoomRange]].txt+" | " + this._frequencyTxtMap[v]
				el.tabmenuZoomEl.find(".rtq-ddl-ipt").html(ss);
			}
           this.setFrequency(v);
        }
    },
	cursorTypeSelected: function(k,v){
		var self = this, el = this._elements, cons  = this._contains, uiComp = this.uiComponents;
		this.setCursorType(parseInt(v,10));
        if (uiComp.rightMenu != null) { 
            uiComp.rightMenu.changeUIState(this.chartCursor,"cursorType",true);
        }
        if (this.chartCursor == 3) {
            cons.pChartContainer.unbind("plothover");
        } else {
			el.crosshairLegendWin.hide();
   			el.lineXElm.hide(), el.lineYElm.hide();
            cons.pChartContainer.unbind("plothover");
            cons.pChartContainer.bind("plothover", function(event, pos, item) {self.buildLegend(item,pos,false,false);});
        }
    },
	chartTypeSelected:function(k,v){
		var el = this._elements, uiComp = this.uiComponents;
        if (this.chartStyle != v) {
            if (uiComp.rightMenu != null) { 
                uiComp.rightMenu.changeUIState(v,"chartType",true);
            }
			if(this.UIConfig.chartCtrl == "rtqPanel" && uiComp.tabMenu != null){
				var i = this.tabIndexMap[v];
				uiComp.tabMenu.changeTabByIndex(i,false);
				if(uiComp.chartTypeMenu[i]!=null){
					var pp = uiComp.tabMenu.getTabById(i).menu.position();
					uiComp.chartTypeMenu[i].setPosition(pp.left,pp.top+23);
					for(var j = 0;j<uiComp.chartTypeMenu.length;j++){
						if(typeof(uiComp.chartTypeMenu[j])!="undefined"){
							uiComp.chartTypeMenu[j].changeUIState(this.chartStyle,null,false);
						}
					}					
					uiComp.chartTypeMenu[i].changeUIState(v,null,true);
				}else{
					for(var j = 0;j<uiComp.chartTypeMenu.length;j++){
						if(typeof(uiComp.chartTypeMenu[j])!="undefined"){
							uiComp.chartTypeMenu[j].changeUIState(this.chartStyle,null,false);
						}
					}	
				}
			}
            this.setChartType(v);
        }
    },
	scaleTypeSelected:function(k,v){
		if(this.scaleType != v){
			this.scaleType = v;
			this.drawPChart();// only draw main chart.
		}
	},
	ratioScaleSelected: function(v){
		var el = this._elements, uiComp = this.uiComponents;
		if(v=="1"){
			el.$ratioScale.find("[value='1']").removeClass("rtq-ratio-off");
			el.$ratioScale.find("[value='0']").addClass("rtq-ratio-off");
		}else if(v=="0"){
			el.$ratioScale.find("[value='0']").removeClass("rtq-ratio-off");
			el.$ratioScale.find("[value='1']").addClass("rtq-ratio-off");
		}
		this.switchScaleType(v);
	},
	ratioYaxisSelected: function(v){
		var el = this._elements, uiComp = this.uiComponents;
		if(v=="right"){
			el.$yaxisAlign.find("[value='right']").removeClass("rtq-ratio-off");
			el.$yaxisAlign.find("[value='left']").addClass("rtq-ratio-off");
	   		el.xLabelElm.css({right:0,left:""});
		}else if(v=="left"){
			el.$yaxisAlign.find("[value='left']").removeClass("rtq-ratio-off");
			el.$yaxisAlign.find("[value='right']").addClass("rtq-ratio-off");
			el.xLabelElm.css({left:0,right:""});
		}
		this.setYaxisAlign(v);
	},
	ratioSelectionModeSelected: function(v){
		var el = this._elements, uiComp = this.uiComponents;
		if(v=="pan"){
			el.$selectionMode.find("a").addClass("rtq-ratio-off");
			this.setSelectionMode(v); 
			el.$selectionMode.find("[value='pan']").removeClass("rtq-ratio-off");
		}else if(v=="zoomin"){
			el.$selectionMode.find("a").addClass("rtq-ratio-off");
			this.setSelectionMode(v);
			el.$selectionMode.find("[value='zoomin']").removeClass("rtq-ratio-off");
		}else if(v=="reset"){
			this.resetZoom()
		}
	},
	showIndicatorWin:function(name) {
		var el = this._elements;
		this._selectedIndicatorName = name;
        if (this.indicatorsData[name] == null || this.indicatorUI[name] == null) {
            return;
        }
		if(name=="SMAV"&&!this.indicatorsData.Volume.show&&!this.indicatorsData.VPlus.show){
			return;
		}
        var oInd = this.indicatorUI[name], aP = oInd.parameter;
		if (typeof(aP)=="undefined" || aP.length == 0) {   // not need input parameters.
			if(this.indicatorsData[name].show){  
				this.removeIndicatorClicked();
			}else{
				this._drawIndicator(name);
			}
		} else {  // show indicator's input window.
			el.indicatorWinElm.find(".qs-ind-title").html(oInd.title); // set title for input window.
			var iV, sStr = "", aDv = oInd.defaultValue, oIndData = this.indicatorsData[name],$rt = el.indicatorWinElm.find(".qs-ind-remove");
            for (var i = 0; i < aP.length; i++){  
               if (name == "EMA"||name == "SMA") {
                   iV = oIndData.num[i] == null?(aDv[i]==null?"":aDv[i]):(oIndData.num[i]==null?"":oIndData.num[i]);
               }else if(name == "SMAV"){
			   	   iV = oIndData.num == null?(aDv[i]==null?"":aDv[i]):(oIndData.num==null?"":oIndData.num);
			   } else {
                   iV = (oIndData.parameter[i] == null?(aDv[i]== null?"":aDv[i]):(oIndData.parameter[i] == null?"":oIndData.parameter[i]));
               }            
               sStr += '<dl><dt>'+aP[i]+'</dt><dd><input type="text" class="qs-ui-ipt p'+i+'" value="'+iV+'" /></dd></dl>';
            }
			el.indicatorWinElm.find(".rtc-win-content").html(sStr);
			el.indicatorWinElm.show();
			if (this.indicatorsData[name].show) {  // remove  button hide or show.
	            $rt.show();
	        } else {
	            $rt.hide();
	        }
		}     
    },
	_drawIndicator:function(sName){   
		var el = this._elements;
		el.indicatorWinElm.hide();
		var isDraw = this.addIndicators(sName);     
        if(isDraw){
			el.indicatorULElm.find("a[value='"+sName+"']").removeClass("rtq-chkbox_off");
			this.changeRightMenuClass(0,sName,true);
			if(sName == "Volume"){
				el.indicatorULElm.find("a[value='VPlus']").addClass("rtq-chkbox_off");
			}else if(sName=="VPlus"){
				el.indicatorULElm.find("a[value='Volume']").addClass("rtq-chkbox_off");
				el.indicatorULElm.find("a[value='SMAV']").removeClass("rtq-chkbox_off");
			}
        }
	},
	cancelIndicator:function() {
        this._elements.indicatorWinElm.hide();
        this._elements.indicatorWinElm.find(".qs-ind-title").html("");
        this._elements.indicatorWinElm.find(".rtc-win-content").html("");
    },
	_setIndicatorParas:function(sName) {  // if not pass parameter or not input paraments in input window it be set to default value.
        var sp, ip, isDraw = false, el = this._elements;
        var oPa = this.indicatorsData[sName];
        var hasInput = false;
		if(arguments.length <= 1 || typeof(arguments[1])=="undefined"){
			hasInput = true;
		}
        if (oPa != null){  // set indicator's parameters from indicator input window.
			if (sName == "SMA"||sName == "EMA") {
	            for (var j = 0; j < oPa.num.length; j++) {
	                sP = hasInput?el.indicatorWinElm.find("input.p"+j).val():arguments[j+1];
	                iP = parseFloat(sP);
	                if (!isNaN(iP)) {
	                    oPa.num[j] = iP;
	                    isDraw = true;
	                } else {
	                    oPa.num[j] = null;
	                }
	            }
	        }else if (sName == "SMAV") {
				var n = parseFloat(hasInput?el.indicatorWinElm.find("input.p0").val():arguments[1]);
		        if(!isNaN(n) && n > 0) {
		            if (oPa && oPa.num != n) { 
			            oPa.num = n;
						isDraw = true;
		        	}
		        }	        
			} else {
				for (var i = 0; i < oPa.parameter.length; i++) {
					sP = hasInput ? el.indicatorWinElm.find("input.p"+i).val() : arguments[i + 1];
					iP = parseFloat(sP);
					if (!isNaN(iP)) {
						oPa.parameter[i] = iP;
					} else {
						oPa.parameter[i] = this.indicatorUI[sName].defaultValue[i];
					}
					isDraw = true;
				}
				if(oPa.parameter.length == 0)isDraw = true;
			} 
		} 
        return isDraw;
    },
	addIndicators: function (sName) {     // add or update technical indicator to chart.
        var name = sName, needDraw = true;
        if(name == "SMA" || name == "EMA") {
            needDraw = this._setIndicatorParas(name,arguments[1],arguments[2],arguments[3]); 
			this.indicatorsData[name].show = true; 
			if(needDraw) this.getPChartData();  
        }else if(name=="Keltner"||name=="PrevClose"){
			needDraw = this._setIndicatorParas(name); 
            this.indicatorsData[name].show = true; 
            if(needDraw) this.getPChartData();
		} else if(name == "SMAV") {
            needDraw = this.indicatorsData[name].show = this._setIndicatorParas(name,arguments[1]);
			if(needDraw) this.getVChartData();  
        } else if(name == "BBands"||name == "PSAR"||name == "MAE"||name=="VBP") {  //need two paras.
            needDraw = this._setIndicatorParas(name,arguments[1],arguments[2]);
            this.indicatorsData[name].show = true; 
            if(needDraw) this.getPChartData();  
        }else if(name == "PChannel"||name== "WMA"){
			needDraw = this._setIndicatorParas(name,arguments[1]);
            this.indicatorsData[name].show = true; 
            if(needDraw) this.getPChartData();  
		}else if(name=="Volume"||name == "VPlus"){  // volume+
			this.indicatorsData[name].show= true;
			if(name == "Volume"){
				this.indicatorsData["VPlus"].show = false;
			}else{
				this.indicatorsData["Volume"].show = false;
				this.indicatorsData["SMAV"].show = true;
				this.indicatorsData["SMAV"].num=50;
			}	
			this.switchVolumeChart(true);
			if(name=="VPlus"){
				this.changeRightMenuClass(2,name,true);
				this.changeRightMenuClass(2,"Volume",false);
				this.changeRightMenuClass(2, "SMAV", true);
			}else{
				this.changeRightMenuClass(2,name,true);
				this.changeRightMenuClass(2,"VPlus",false);
			}
			this.getVChartData();
			needDraw = true;
		}else if(this.iFlots.hasOwnProperty(name)) {  // add new indicator chart.
            if(name == "MACD") {
                needDraw = this._setIndicatorParas(name,arguments[1],arguments[2],arguments[3]);
            } else if(name == "RSI"||name=="ROC"||name=="WillR"||name=="MFI"||name=="Momentum"||name=="ForceIndex") {
                needDraw = this._setIndicatorParas(name,arguments[1]);
            } else if(name=="ULT"||name=="DMI"||name=="OBV"||name=="VAcc"||name=="AccDis"||name=="Mass"||name=="ATR"){ // not need input parameter
				needDraw = this._setIndicatorParas(name);
			} else if(name == "SStochastic" || name=="FStochastic"||name== "UDRatio"||name== "Volatility") {
                needDraw = this._setIndicatorParas(name,arguments[1],arguments[2]);
            } 
			if(needDraw){ // draw a new indicator chart
				if(this.UIConfig.autoHeight && !this.indicatorsData[name].show) {
	                this.outHeight += this.iChartHeight;
	            }
				this.indicatorsData[name].show = true;
	            this.setSize(this.chartWidth,this.outHeight);
	            if(this.pFlot != null){ 
	                this.pFlot.resizeCanvas(this.chartWidth,this.pChartHeight);
	            }
	            if(this.vFlot != null && this.showVolume) {
	                this.vFlot.resizeCanvas(this.chartWidth,this.vChartHeight);
	            }
				this.drawPChart();
				if(this.showVolume)this.drawVChart();
				this.getIChartData(name);
			}   
            
        }
		if(typeof(this.afterAddIndicators)== "function"){  // after callback;
			this.afterAddIndicators({indicatorName:name,paras:arguments});
		}
		return needDraw;
    },
	removeIndicators: function (name) {
		var needChangeUi = false;
		if(name =="SMAV") {
		 	this.indicatorsData.SMAV["num"] = null;
			this.indicatorsData[name].show= false;
            this.getVChartData();
			needChangeUi = true;
        }else if(name == "SMA"||name=="EMA") {     // remove a overlay indicator chart.
        	var num = null,needDraw = false;
			needChangeUi = true;
            if(arguments.length > 1&& typeof(arguments[1])!="undefined"&& arguments[1]!=null) {
                num = parseInt(arguments[1],10);  // remove one of ema lines.
            }
			for (i = 0; i < this.indicatorsData[name]["num"].length; i++) { 
                if (num!=null){
					if (this.indicatorsData[name].num[i] == num) {
						this.indicatorsData[name].num[i] = null;
						this._removeDataRowFromDataList(name,i);
						needDraw = true;
					}
					if (this.indicatorsData[name].num[i] != null){
                    	needChangeUi = false;   // exisit
						needDraw = true;
                	} 
                }else {
					this.indicatorsData[name].num[i] = null;  // remove all EMA lines
					this._removeDataRowFromDataList(name,i);
					needDraw = true;
				}   
            }
			if(needChangeUi)this.indicatorsData[name].show = false;
			if(needDraw) this.drawPChart();       
        } else if(name == "PSAR" || name == "BBands"||name == "PChannel" || name == "MAE"||name=="VBP"||name == "WMA"||name=="Keltner"||name=="PrevClose") {
            for (var i = 0; i < this.indicatorsData[name].parameter.length; i++) { 
                this.indicatorsData[name].parameter[i] = null;
            }
			this._removeDataRowFromDataList(name);
			this.drawPChart();
			this.indicatorsData[name].show= false;
			needChangeUi = true;
    	} else if(name=="Volume"||name=="VPlus"){// remove volmue chart (hide)
			this.indicatorsData[name].show= false;
			this.switchVolumeChart(false);
			if(name=="Volume"){
				this.changeRightMenuClass(2,name,false);
			}else{
				this.changeRightMenuClass(2,name,false);
			}
			this.indicatorsData["SMAV"].show = false, this.indicatorsData["SMAV"].num = null;
			needChangeUi = true;
	    }else if(this.indicatorsData[name]) { // remove a new indicator chart
            this.removeIChart(name);
			needChangeUi = true        
        } 
        if(typeof(this.afterRemoveIndicators)== "function"){  // after callback;
			this.afterRemoveIndicators({indicatorName:name,paras:arguments});
		}
		return needChangeUi;
    },
	//get chart data interfaces
   _convertToEventData: function(data,priceData) {
        var d, cd = this.chartData; 
        cd.eventDataList = [],cd.eventInfoList={};
        for(var o in data){
            d = data[o];
            if(!d) continue;
            var k = 0,sq=0;
            for(i = 0; i < d.length; i++){   
                var index = o=="earnings"?d[i][d[i].length-1]:d[i].DateIndex;
                var ls = priceData[0][priceData[0].length-1];
                for(var j = k;j < priceData.length; j++){
                    if (j > 0) {
                        ls = priceData[j-1][priceData[j-1].length-1];
                    }
                    if (index <= priceData[j][priceData[j].length - 1] && index >= ls) {
                        sq = priceData[j][0];
                        if(typeof(cd.eventDataList[sq])=="undefined"){
                            cd.eventDataList[sq]=[sq];
                        }
                        if(typeof(cd.eventInfoList[sq])=="undefined"){
                            cd.eventInfoList[sq]=[];
                        }
                        if(o=="earnings"){
                            cd.eventDataList[sq].push(d[i][2]==0?3:4);
                            cd.eventInfoList[sq].push({name:"Earnings:",type:d[i][2]==0?3:4,val:d[i][1],dIndex:index});
                        }else if(o=="ds"){
                            cd.eventDataList[sq].push(d[i].Type); // 1: dividend 2: spilt.
                            cd.eventInfoList[sq].push({name:(d[i].Type == 1 ? "Dividend:" : "Splits:"),
                                val:d[i].Desc,type:d[i].Type,dIndex:index});
                        }           
                        k=j;
                        break;
                    }
                    
                }
            }
        }
    },
	setLineColors:function(aColors){
		if (typeof(aColors) == "object" && aColors.length) {
			this.tickerColors = aColors;
		}
	},
	setFillColors: function(type,value){
		this.fillColors[type] = value;
	},
	setColors:function(type,value){
		this.colors[type]=value
	},
	setYaxisAlign:function(align){
		this.yaxisAlign = align;
		this.freshAllCharts(align);
	},
	switchShowLastLabel: function(isShow){
		this.isShowLastLabel = isShow;
	},
	setCursorType: function(iTy) {
        this.chartCursor = iTy;
		if(this.pFlot!=null)this.pFlot.setOption({imageHighlight:(iTy==0)});
		this.mouseOutChart();
    },
	setChartType: function(v){
		if (this.chartStyle != v) {
			var oldStyle = this.chartStyle;
            this.chartStyle = v;
			if(this.compairTickers.length||v=="postTax"||oldStyle == "postTax"||v=="growth10"||oldStyle == "growth10"||v=="growth"||oldStyle == "growth"||v=="dEffect"||oldStyle == "dEffect"){
				this.getPChartData();
			}else {
                this.drawPChart();
            }
			if(typeof(this.afterChartTypeChanged)== "function"){
				this.afterChartTypeChanged({chartType:this.chartStyle});
			}
        }
    },
	setFrequency: function(f) {
	 	if (this.frequency != f&& typeof(this._frequencyIndexMap[f])!="undefined") { 
			if(this._frequencyIndexMap[self.frequency]>0){
                this._clearZoomIn(); 
            }else{
                this._changeZoomInIndex(this.frequency,f); 
            }
            this.frequency = f;
            this.drawChartSegment(); // refreash all data.
        }
    },
	switchScaleType: function(va){
		var v = parseInt(va,10);
		if(v != 0 && v != 1)return false;
		if(this.scaleType != v){
			this.scaleType = v;
			this.drawPChart();// only draw main chart.
		}
	},
	switchIIV:function(v){
		this.showIIVTicker = (v==1||v==true);
		this.getPChartData();
	},
	setSelectionMode:function(v){ // "pan" or "zoomin". default value is 0;
	    if(v=="pan"){
			this.selectionMode.pan = true,this.selectionMode.zoomIn = false, this.selectionMode.reset=false; 
		}else if(v=="zoomin"){
			this.selectionMode.pan = false,this.selectionMode.zoomIn = true, this.selectionMode.reset=false; 
		}	
	},
	resetZoom:function(){  //
		this.selectionMode.reset = true;
        this._resetZoomChart();
	},
	switchEvents:function(name,bshow){  // 1: show, 0:hide.
		var b = (bshow == 1);
		 if(this.events[name] != b){
            this.events[name] = b; 
            if(this.zoomRange > 2) this.getPChartData();
			if(typeof(this.eventsChanged) == "function"){
				this.eventsChanged({eventName:name,show:b});
			}
        }
	},
	addCompairTickers:function(symbols) {         // add compair tickers.
    	this.validateCompairTicker(symbols);
    },
    removeMainTicker:function(isUseCompairTickerAsMainTicker){
        if(isUseCompairTickerAsMainTicker&&this.compairTickers.length){  // use the first of compaire ticker as mainticker.
            var t = this.compairTickers[0];
            this.compairTickers.splice(0,1);
            this.acceptTicker(t);
        }else{   // no main ticker clear the chart.
            GB_ChartDataManager.unregisterSymbol(self.mainTicker);
            GB_ChartDataManager.unregisterChart(self.mainTicker,self.id);
            this.bacthUnscribeTickers([this.mainTicker]);
            delete this.tickerInfos[this.mainTicker];
            if (this.pFlot != null) {
                this.pFlot.clear(),this.pFlot = null;
            }
            if (this.vFlot != null) {
                this.vFlot.clear(),this.vFlot = null;
            } 
            if (this.mFlot != null) {
                this.mFlot.clear(),this.mFlot = null;
            }
            for(var o in this.iFlots) {
                if(this.iFlots.hasOwnProperty(o) && this.iFlots[o] != null) {
                    if(this.iChartContainers[o]!= null)this.iChartContainers[o].find(".lengend").unbind("click").unbind("hover").unbind("contextmenu");
                    this.iFlots[o].clear(),this.iFlots[o]=null;
                }
            }
            this.mainTicker = "";
            if(this._elements.legendElm)this._elements.legendElm.html("");
            if(this._elements.volLegendElm)this._elements.volLegendElm.html("");
        }
        
    },
	removeCompairTicker: function(ticker) {           // remove a compair ticker.
        if(this.compairTickers == null || this.compairTickers.length < 1) {
            return;
        }
		var t = ticker;
		if(ticker.split(":").length == 2){   // exch:ticker
			t = this.getPidByExchAndTicker(ticker);    // convert to performanceId.
		}
        for(var i = 0; i < this.compairTickers.length; i++) {
            if(t == this.compairTickers[i]){
				if(typeof(this.afterRemoveTickers)== "function"){  // after callback;
					this.afterRemoveTickers({symbol:this.tickerInfos[t]});
				}
				GB_ChartDataManager.unregisterSymbol(this.compairTickers[i]);
		        this.bacthUnscribeTickers([this.compairTickers[i]]);
				delete this.tickerInfos[this.compairTickers[i]];   
		        this.compairTickers.splice(i,1);
				if(this.compairTickers.length){
					this._removeDataRowFromDataList(t);
					this.drawPChart();
				}else{
					this.getPChartData(); // refresh data. convert return to price type.
				}
                break;
            }
        }		
    },
	changeDatePeriod: function (s,e) {   // customize date range. date format: (yyyy-MM-dd)
        this.startDate = RTQ_ChartUtil.convertToDate(s);
        this.endDate = RTQ_ChartUtil.convertToDate(e);
        this.changeRange(11); 
		if(typeof(this.datePeriodChanged) == "function" ){
			this.datePeriodChanged({zoomRange:this.zoomRange,startDate:s,endDate:e});
		}
		this._clearZoomIn(); // clear the zoom in stack.
    },
	changeRange:function(num,freq) {  // freq can be null or undefined.
		if(this.mainTicker==null||this.mainTicker=="") return;
		if(num!=11){  // not customize  the data clear the zoom in stack.
			this._clearZoomIn();
		}
		var uiComp = this.uiComponents;
		if (uiComp.rightMenu != null) {
			uiComp.rightMenu.changeUIState(this.frequency,this.zoomRange,false);
		}
		if(uiComp.tabZoomMenu!=null){
			uiComp.tabZoomMenu.changeUIState(this.frequency,this.zoomRange,false);
		}
        this.zoomRange = num;
        if (num != 11) {
            this.endDate = this.latestTradeDate;
        }
		var y = this.endDate.getFullYear(), m = this.endDate.getMonth(),d = this.endDate.getDate();
        if(num == 1) {
            this.startDate = this.endDate;
        } else if (num == 2) {
            this.startDate = new Date(y, m, d-5);
        }else if (num == 0) { // 3 days
            this.startDate = new Date(y, m, d-3);
        } else if (num == 13) {  // 15 days
            this.startDate = new Date(y, m, d-15);
        }  else if (num == 3) {
            this.startDate= new Date(y, m-1, d); 
        } else if (num == 14) { // 2 mth
            this.startDate= new Date(y, m-2, d); 
        } else if (num == 4) {
            this.startDate = new Date(y, m-3, d);
        } else if (num == 5) { 
            this.startDate = new Date(y, 0, 1); 
        } else if (num == 6) {
            this.startDate= new Date(y - 1, m, d);
        } else if (num == 7) {
           this.startDate = new Date(y - 3, m, d);
        } else if (num == 8) {
            this.startDate = new Date(y - 5, m,d);
        } else if (num == 9) {
            this.startDate = new Date(y - 10, m, d);
        } else if (num == 10) {
            this.startDate = new Date(1970, 0, 1); 
        } else if (num == 11) { // custom.
            if (uiComp.ddlZoom != null) {
				uiComp.ddlZoom.setTextValue("Custom","11");
			}
        }
        if(typeof(freq)!="undefined"&&this._frequencyIndexMap[freq]!=null){
            this.frequency = freq;
            this.customizeFreq = true;
        }else{
            this.customizeFreq = false;
        }
        this.changeFrequencyStyle(num);
		this.drawChartSegment();
		if(typeof(this.datePeriodChanged)== "function"){  // after callback;
			this.datePeriodChanged({zoomRange:this.zoomRange,startDate:RTQ_ChartUtil.formatDate(this.startDate),
				endDate:RTQ_ChartUtil.formatDate(this.endDate)});
		}
    },
	beginDrawing: function(type){
		if (this.pFlot!=null) {
			this.pFlot.beginDrawing(type);
			this.isDrawing = true;
		}
	},
	cancelDrawing: function(type){
		if (this.pFlot!=null) {
			this.pFlot.cancelDrawing(type);
			this.isDrawing = false;
		}
	},
	drawChartSegment:function(){
		this.chartData.fairValueData = null;
		var self = this;
		this.getPChartData(function(){
			for(var o in self.indicatorsData){
				if(self.indicatorsData[o].type==1&&self.indicatorsData[o].show){
					self.getIChartData(o);
				}
			}
			if(typeof(self.valuations)!="undefined"){
				for(var o in self.valuations){
					if((self.valuations[o]&& self.valuations[o].show)){
						self.getIChartData(o);
					}
				}
			}		
		});
	},
	_getDataBySymbol:function(dataList,symbol){
		for(var i=0;i<dataList.length;i++){
			if(dataList[i].symbol == symbol){
				return dataList[i];
			}
		}
		return null;
	},
    _getClientTicker:function(symbol){
        return (this.tickerInfos[symbol].clientTicker||this.tickerInfos[symbol].ticker);
    },
	pChartDataReady: function(data,successCallback){
		/*if(typeof(data.length)=="undefined"&&data.errorCode!=0){
			this.zoomRange=3;
			this.reBindFrequencyMenuData({intraday:false});
			this.changeRange(this.zoomRange,"d");
			return ;
		}*/
		var cd = this.chartData;
		var mainData = this._getDataBySymbol(data,this.mainTicker),compData,cloIndx=0;
		if(typeof(mainData.price.lastTradeDate)!= "undefined" && mainData.price.lastTradeDate!= this.latestTradeDate){
			this.refreshLastTradeDate(null,mainData.price.lastTradeDate);
		}
		cd.DataList = [];
		if(mainData){
			if(mainData.price){
			var lg = this._getClientTicker(this.mainTicker);//this.tickerInfos[this.mainTicker].ticker;
           		cd.DataList.push({data:mainData.price.data,startPos:mainData.price.spos,colorIndex:0,
					color:this.tickerColors[0],name:this.mainTicker,legend:lg,freq:mainData.price.freq}); 
				cloIndx++;
				// custom date or max date
				if((this.zoomRange<=2||this.zoomRange >9) && mainData.price.data!=null&& mainData.price.data.length){ 
					var dtt;
					if(this._frequencyIndexMap[this.frequency]>0){
						dtt = RTQ_ChartUtil.toDateFromIndex(mainData.price.data[0][mainData.price.data[0].length-1]);
					}else{
						var tempDt = new Date(mainData.price.data[0][mainData.price.data[0].length-1]);
						dtt = new Date(tempDt.getFullYear(),tempDt.getMonth(),tempDt.getDate());
					}
					if(this.startDate!=dtt){
						this.startDate = dtt;
						if(this.uiComponents.customDateB!=null)this.uiComponents.customDateB.setDate(this.startDate,this.endDate);
					}
				}
			}	
		}
		if(this.showIIVTicker){
			var iivData = this._getDataBySymbol(data,this.iivTicker);
			if(iivData&&iivData.price){
				lg = this._frequencyIndexMap[this.frequency]>0?QSLGTXT.nav:QSLGTXT.inav;//this.tickerInfos[this.iivTicker].ticker;
				if(this.UIConfig.IIVLegend=="ticker"){  // qs 
					lg = this._getClientTicker(this.iivTicker)+"("+(this._frequencyIndexMap[this.frequency]>0?QSLGTXT.nav:QSLGTXT.inav)+")";
				}
				cd.DataList.push({data:iivData.price.data,startPos:iivData.price.spos,colorIndex:cloIndx,
				color:this.tickerColors[cloIndx],name:"_iiv",legend:lg});
				cloIndx++;
			}	
		}
		if(this.compairTickers.length){
			for(var i = 0; i< this.compairTickers.length;i++){
				compData = this._getDataBySymbol(data,this.compairTickers[i]);
				if(compData&&compData.price){
					lg = this._getClientTicker(this.compairTickers[i]);//this.tickerInfos[this.compairTickers[i]].ticker;
					cd.DataList.push({data:compData.price.data,startPos:compData.price.spos,colorIndex:cloIndx,
						color:this.tickerColors[cloIndx],name:this.compairTickers[i],legend:lg});
					cloIndx++; 
				}
			}
		}
	   var eventData = {},hasEvent=false;
	   if(this.events.earnings){
	   		if(mainData.earningsData){
				eventData["earnings"]= mainData.earningsData.data, hasEvent=true;
			}
	   }
	   if (this.events.dividend || this.events.splits) {
			if(mainData.dividendAndSplit){
				eventData["ds"]= mainData.dividendAndSplit,hasEvent=true;
			}
       }
	   if(hasEvent) this._convertToEventData(eventData,mainData.price.data);
		if(mainData!=null&& mainData.indicators){
			if(mainData.indicators["SMA"]){
				var lg = this.indicatorsData.SMA.num.length, d,num; 
	            for (var k = 0; k< lg; k++) {
					num = this.indicatorsData.SMA.num[k];
	                if (num != null&& mainData.indicators["SMA"][num]) { 
						cd.DataList.push({data:mainData.indicators["SMA"][num].data,
							startPos:mainData.indicators["SMA"][num].spos,colorIndex:cloIndx,
							color:this.tickerColors[cloIndx],legend:QSLGIN.sma_lg+"("+num+")",name:"SMA",sq:k,num:num});
						cloIndx++
	                }
	            }
			}
			if(mainData.indicators["EMA"]){
				var lg = this.indicatorsData.EMA.num.length, d,num; 
				for (var j = 0; j< lg; j++) {
					num = this.indicatorsData.EMA.num[j];
	                if (num != null&& mainData.indicators["EMA"][num]) { 
						cd.DataList.push({data:mainData.indicators["EMA"][num].data,
							startPos:mainData.indicators["EMA"][num].spos,colorIndex:cloIndx,
							color:this.tickerColors[cloIndx],legend:QSLGIN.ema_lg+"("+num+")",name:"EMA",sq:j,num:num});
						cloIndx++;
	                }
	            }
			}
			if(mainData.indicators["WMA"]) {     
				var l = QSLGIN.wma_lg+"("+this.indicatorsData.WMA.parameter[0]+")"; 
				cd.DataList.push({data:mainData.indicators["WMA"].data,startPos:mainData.indicators["WMA"].spos,
					colorIndex:cloIndx,color:this.tickerColors[cloIndx],legend:l,name:"WMA"});
	            cloIndx++;
	        }
			if (mainData.indicators["Keltner"]) {
				var preL = QSLGIN.keltner_lg+"("+this.indicatorsData.Keltner.parameter[0]+","+this.indicatorsData.Keltner.parameter[1]+","+this.indicatorsData.Keltner.parameter[2]+")";
				var d1 = mainData.indicators["Keltner"][0], d2 = mainData.indicators["Keltner"][2], d3 = mainData.indicators["Keltner"][1];
				cd.DataList.push({data:d1.data,startPos:mainData.indicators["Keltner"],colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"U",name:"Keltner",sq:0});
				cd.DataList.push({data:d2.data,startPos:mainData.indicators["Keltner"],colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"L",name:"Keltner",sq:1});
				cloIndx++;
				cd.DataList.push({data:d3.data,startPos:mainData.indicators["Keltner"],colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:QSLGIN.ema_lg+"("+this.indicatorsData.Keltner.parameter[0]+")("+QSLGIN.keltner_lg+")",legend:QSLGIN.keltner_lg,name:"Keltner",sq:2});	
	            cloIndx++;
				//this.addIndicators("EMA",this.indicatorsData.Keltner.parameter[1]);
	        }
			if (mainData.indicators["BBands"]) {
				var preL = QSLGIN.bbands_lg+"("+this.indicatorsData.BBands.parameter[0]+","+this.indicatorsData.BBands.parameter[1]+")";
				var d1 = mainData.indicators["BBands"][0], d2 = mainData.indicators["BBands"][1];
				cd.DataList.push({data:d1.data,startPos:d1.spos,colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"U",name:"BBands",sq:0});
				cd.DataList.push({data:d2.data,startPos:d2.spos,colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"L",name:"BBands",sq:1});
	            cloIndx++;
	        }
	        if (mainData.indicators["PSAR"]) {     
				var l = QSLGIN.psar_lg+"("+this.indicatorsData.PSAR.parameter[0]+","+this.indicatorsData.PSAR.parameter[1]+")"; 
				cd.DataList.push({data:mainData.indicators["PSAR"].data,startPos:mainData.indicators["PSAR"].spos,
					colorIndex:cloIndx,color:this.tickerColors[cloIndx],legend:l,name:"PSAR"});
	            cloIndx++;
	        }
			if (mainData.indicators["PChannel"]) {
				var preL = QSLGIN.pchannel_lg+"("+this.indicatorsData.PChannel.parameter[0]+")";
				var d1 = mainData.indicators["PChannel"][0], d2 = mainData.indicators["PChannel"][1];
				cd.DataList.push({data:d1.data,startPos:d1.spos,colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"U",name:"PChannel",sq:0});
				cd.DataList.push({data:d2.data,startPos:d2.spos,colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"L",name:"PChannel",sq:1});
	            cloIndx++;
	        }
			if (mainData.indicators["MAE"]) {
				var preL = QSLGIN.mae_lg+"("+this.indicatorsData.MAE.parameter[0]+","+this.indicatorsData.MAE.parameter[1]+"%)";
				var d1 = mainData.indicators["MAE"][0], d2 = mainData.indicators["MAE"][1];
				cd.DataList.push({data:d1.data,startPos:d1.spos,colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"U",name:"MAE",sq:0});
				cd.DataList.push({data:d2.data,startPos:d2.spos,colorIndex:cloIndx,color:this.tickerColors[cloIndx],
					pre:preL,legend:"L",name:"MAE",sq:1});
	            cloIndx++;
	        }
			if(mainData.indicators["PrevClose"]){
				cd.DataList.push({data:mainData.indicators["PrevClose"].data,startPos:mainData.indicators["PrevClose"].spos,
                colorIndex:18,color:this.tickerColors[18],legend:QSLGIN.prevclose_lg,name:"PrevClose"});  
			}
			if(!this.compairTickers.length && mainData.indicators["VBP"]){
				var l = "VBP";
				cd.DataList.push({data:mainData.indicators["VBP"].data,startPos:null,colorIndex:17,
					color:this.tickerColors[17],legend:l,name:"VBP",sq:0});
	            cloIndx++;
			}
			if(this.chartData.fairValueData!=null&& this.valuations["FairValue"].show && this.zoomRange>2&&!this.compairTickers.length){
				if(this.chartData.DataList.length&&this.chartData.DataList[0].freq == this.chartData.fairValueData.freq){
					this.chartData.DataList.push({data:this.chartData.fairValueData.data,startPos:this.chartData.fairValueData.spos,
						colorIndex:15,color:this.tickerColors[15],legend:QSLGFD.fairvalue_name,name:"FairValue"});
				}	
			}
			
		}
		var needDrawP = false;
		if(this.chartStyle == "dEffect"){
			if(this.zoomRange > 2&& this._frequencyIndexMap[this.frequency]>0){ 
				this.getIChartData("MReturnIndex");
			}else{                           
				this.chartData.DataList.push($.extend(true,{},this.chartData.DataList[0]));
				this.chartData.DataList[1].legend = this.chartData.DataList[1].legend+"(w/o Div.)";
				this.chartData.DataList[1].name = "MReturnIndex";
				needDrawP=true;
				
			}
		}else{
			needDrawP=true;
		}
		if(needDrawP){
			if(this.zoomInMode==1&&this.zoomIndexRange){  // zoom in one day chart.
	            this._zoomInData(this.zoomIndexRange.s,this.zoomIndexRange.e,this.chartData.DataList);
	        }
			this.drawPChart();
		}
		if(mainData&&mainData.volume){
			this.chartData.VolList = [];
			mainData.volume.name = "volume";
			this.chartData.VolList.push({data: mainData.volume.data,name: "volume",startPos: null,legend: QSLGIN.volume_lg});
			if (mainData.indicators && mainData.indicators["SMAV"]){
				var leg = QSLGIN.smav_lg+"("+this.indicatorsData.SMAV.num+")";
				this.chartData.VolList.push({data:mainData.indicators["SMAV"].data,startPos:null,name:"SMAV",legend:leg});
			}
			if(this.zoomInMode==1&&this.zoomIndexRange){  // zoom in one day chart.
                this._zoomInData(this.zoomIndexRange.s,this.zoomIndexRange.e,this.chartData.VolList);
            }
			this.drawVChart();
		}
		if(typeof(successCallback)=="function"){  // success callback
			successCallback();
		}
		if(typeof(this.hideLoading) == 'function') {
			this.hideLoading();
		}
		if(typeof(this.afterChartOnReady)=="function"){
			this.afterChartOnReady();
		}
		if(data.length>0&&this.showNotes){
			this._loadChartNote(this.mainTicker);
		}
		
	},
	_loadChartNote:function(ticker){
        var self = this;
		self._contains.pChartContainer.find(".qs-note-flot").remove();
        var startDate = this.startDate.getTime(), endDate = this.endDate.getTime();
		if(startDate==endDate){
			endDate = startDate+(24*60*60*1000);
		}
        GB_ChartDataManager.getChartNoteData(startDate, endDate, ticker, function(cdate){
            self.pFlot.renderNote(cdate);
        })
	},
	iChartDataReady: function(data){
		var da = null, cd = this.chartData;
		if(data.length){
			da = data[0].indicators;		
		}else{
			da = data;
		}
		for(var o in da){	
			if(o=="FairValue"){  // draw fair value line in Price Chart. delay 500 ms to wait the price data arrived.
				cd.fairValueData = da[o];
				cd.fairValueData.freq = this.frequency;
				if(!this.compairTickers.length && this.zoomRange>2 && cd.DataList!=null && cd.DataList.length &&
					cd.DataList[0].freq == cd.fairValueData.freq){
					cd.DataList.push({data:cd.fairValueData.data,startPos:cd.fairValueData.spos,
						colorIndex:15,color:this.tickerColors[11],legend:QSLGFD.fairvalue_name,name:"FairValue"});
				    this.drawPChart();
				}				
			}else if(o=="MReturnIndex"){
				cd.mReturnIndexData = da[o];
				cd.mReturnIndexData.freq = this.frequency;
				if(cd.DataList.length&&cd.DataList[0].freq == cd.mReturnIndexData.freq){
					if (this.zoomInMode == 1 && this.zoomIndexRange) { // zoom in one day chart.
						this._zoomInDataItem(this.zoomIndexRange.s, this.zoomIndexRange.e, cd.mReturnIndexData);
					}
					cd.DataList.push({data:cd.mReturnIndexData.data,startPos:cd.mReturnIndexData.spos,colorIndex:0,
					color:this.tickerColors[0],legend:this._getClientTicker(this.mainTicker)+"(w/o Div.)",name:"MReturnIndex"});
				    this.drawPChart();
				}
			} else {
				this.iChartData[o]= da[o]&&da[o].length?da[o]:[da[o]];
				if(this.zoomInMode==1&&this.zoomIndexRange){  // zoom in one day chart.
                    this._zoomInData(this.zoomIndexRange.s,this.zoomIndexRange.e,this.iChartData[o]);
                }
				this.drawIChart(o);
			}	
		}
	},
	drawIChart:function(sName) {  // draw indicator or valuation chart.
    	var cd = this.chartData, self = this, cons = this._contains, el = this._elements,uiComp = this.uiComponents;  // new charts
        if ((this.indicatorsData[sName]&& this.indicatorsData[sName].show)|| (this.valuations&&this.valuations[sName]&& this.valuations[sName].show)) {
			var oFlot = this.iFlots[sName];
            if (oFlot == null) { 
                var option = this.getChartOption("indicatorLines");
				this.iChartContainers[sName] = $('<div class="rtc-chart-container" name='+sName+'>'+
					'<div class="legend" >'+sName+'</div><div class="rtc-chart rtc-chart-mini"></div></div>');
                var cobj = this.iChartContainers[sName].find(".rtc-chart");
				if((this.UIConfig.Chart&&this.UIConfig.Chart.showTimeSlider)||this.UIConfig.chartCtrl=="rtqPanel"){
					cons.mChartContainer.parent().before(this.iChartContainers[sName]);
				}else{
					this.outObj.append(this.iChartContainers[sName]);
				}	
				this.iChartContainers[sName].find(".legend").bind("click",function(e){
					self.iChartLegendOnclick($(this).parent().attr("name"));
					}).hover(function(e){
					$(this).addClass("rtc-legend-remove");
				},function(e){
					$(this).removeClass("rtc-legend-remove");
				});
				cobj.css({width:this.chartWidth+"px",height:"60px"})
				oFlot = this.iFlots[sName] = new mstar.flot(cobj,option);
				if (this.UIConfig.RightMenu) { 
					this.iChartContainers[sName].bind("contextmenu", function(e){
						var idx = 0, name = $(this).attr("name");
						uiComp.miniChartRightMenu.menu.show(e);
						uiComp.miniChartRightMenu.owner = name;
						e.preventDefault();
					});
				}
            } else {
				this.iChartContainers[sName].attr("name",sName);
                this.iChartContainers[sName].show();
                this.iChartContainers[sName].find(".rtc-chart").css({width:this.chartWidth+"px"}).show();
            }
            if (this.iChartData[sName]&&this.iChartData[sName].length) {
				this.iChartContainers[sName].attr("name",sName);
                oFlot.setOption({xaxis:{tickSize:this.ticksize,ticks:this.Ticks}});
				if (sName == "WillR") {
                    oFlot.setOption({yaxis: {ticks: [-50, -100],min:-100,max:0}}); // specil the yaxis for willR indicator chart.
                }else{
					oFlot.setOption({yaxis: {ticks: null,min:null,max:null}});
				}  
				var aIndData = this.iChartData[sName];
                var aChartData = []; 
				for(var i=0;i<aIndData.length;i++){
					aChartData[i]= aIndData[i]==null?null:aIndData[i].data;
					if(i == 2 && sName == "MACD")aChartData[i] = this.getChartData((aIndData[i]==null?null:aIndData[i].data),"bars",1,null);
				}
				oFlot.setOption({yaxis: {align: this.yaxisAlign}});
                oFlot.init(aChartData);  
				this.buildIChartLegend(-1);     
            }
        }
    },
	_drawAllICharts:function(){
		for(var o in this.indicatorsData){
			if(this.indicatorsData[o].type==1&&this.indicatorsData[o].show){
				this.drawIChart(o);
			}
		}
		if(typeof(this.valuations)!= "undefined"){
			for(var o in this.valuations){
				if((this.valuations[o]&& this.valuations[o].show)){
					this.drawIChart(o);
				}
			}
		}
	},
	freshAllCharts:function(){
		this.drawPChart();
		if(typeof(this.drawVChart)=="function")this.drawVChart();
		this._drawAllICharts();
	},
	getMiniTickSize: function() {
		if(this.miniChartFrequency == "minute")return 23;
        else if (this.miniChartFrequency == "d") return 54;
        else if (this.miniChartFrequency == "w") return 10;
        else if (this.miniChartFrequency == "m") return 10;
        else return 10;
    },
	tickFormat: function(v) {
		var cd = this.chartData,d="";
        if (cd.DataList != null && cd.DataList[0].data != null && v < cd.DataList[0].data.length && 
			cd.DataList[0].data[v] != null && cd.DataList[0].data[v].length) {
			d = RTQ_ChartUtil.formatPChartXLabel(cd.DataList[0].data[v][cd.DataList[0].data[v].length-1],this.zoomRange,this._isIntradayTimSyle);
        } 
		return d;   
    },
	getChartOption: function(type)  { // get the config for chart.
		var cd = this.chartData, self = this;
        if (type == "priceLine") {
           return { xaxis: { mode:null,tickSize:this.ticksize,showLabel:true,labelWidth:60,labelHeight:12,ticks:this.Ticks,
                       tickFormatter:function(v){return self.tickFormat(v);}},
                       yaxis: {labelWidth:this.yLabelWidth,labelHeight:12,align:this.yaxisAlign,showLastLabel:this.isShowLastLabel,
                       labelFormatter:function(v){return QS_NumFmt.Fmt2(v,true," ",self.precision||2)}},          //
                       grid: { hoverable: true, clickable: true,color:this.colors.lableFontColor,tickColor:this.colors.gridColor,_borderColor:this.colors.borderColor},
					   colors:this.tickerColors,
				   	   candleStick:{upColor:typeof(QS_Style)!="undefined"&&QS_Style.greenFontColor?QS_Style.greenFontColor:"#008000",
	        		   downColor:typeof(QS_Style)!="undefined"&&QS_Style.redFontColor?QS_Style.redFontColor:"#ff0000"},
                       showGridLines:this.showGridLines			   		
                    };
        } else if (type == "indicatorLines") {
           return { xaxis: { mode:null,tickSize:this.ticksize,showLabel:false,ticks:this.Ticks,
                      tickFormatter:null},
                      lines: {lineWidth:1,lineType:"line"},
                      yaxis: {labelWidth:this.yLabelWidth,labelHeight:12,align:this.yaxisAlign,showLastLabel:this.isShowLastLabel,
                      labelFormatter:function(v){return QS_NumFmt.Fmt2(v,true," ",self.precision||2);}},
					  grid: {color:this.colors.lableFontColor,tickColor:this.colors.gridColor,_borderColor:this.colors.borderColor},
					  colors:this.tickerColors,
                      showGridLines:this.showGridLines          
                    }
					;    
        } else if (type == "volumeBar") {
           return { xaxis: { mode:null,tickSize:this.ticksize,showLabel:false,ticks:this.Ticks,
                      tickFormatter:null},       
                      yaxis: {labelWidth:this.yLabelWidth,labelHeight:12,min:0,align:this.yaxisAlign,showLastLabel:this.isShowLastLabel,labelFormatter:function(v){
					  	return QS_NumFmt.Fmt(Math.round(v * 1000000), true)
					  }},        
                      bars:{show:false,barWidth:1.5,lineWidth:0,fillColor:this.fillColors.vChart,isColorBar:true,
					       upColor:typeof(QS_Style)!="undefined"&&QS_Style.greenFontColor?QS_Style.greenFontColor:"#008000",
	        		       downColor:typeof(QS_Style)!="undefined"&&QS_Style.redFontColor?QS_Style.redFontColor:"#ff0000"	},
					 grid: {color:this.colors.lableFontColor,tickColor:this.colors.gridColor,_borderColor:this.colors.borderColor},
					 colors:this.tickerColors,
                     showGridLines:this.showGridLines 
                    };
        }  else if (type == "miniChart") {  // sildd chart.
            return { xaxis: { mode:null,tickSize:this.getMiniTickSize(),showLabel:true, tickFormatter:function(v){
		                 if(cd.MiniChartData.length&&cd.MiniChartData[0]!=null&&cd.MiniChartData[0].length>v&&cd.MiniChartData[0][v].length)
						 	return RTQ_ChartUtil.formatSChartXLabel(cd.MiniChartData[0][v][cd.MiniChartData[0][v].length-1],self.miniChartFrequency);
						 },labelWidth:50,labelHeight:8,posStyle:"inner"},       
                       yaxis: {labelWidth:0,labelHeight:12,showLabel:0,autoscaleMargin: 0.02,ticks:[],align:this.yaxisAlign},        
                       lines:{fill:true,noLine:true,fillColor:this.fillColors.sChart,a:1},
					   colors:this.tickerColors,
					   grid:{borderWidth:0,color:this.colors.lableFontColor,tickColor:this.colors.gridColor,_borderColor:this.colors.borderColor},
                       showGridLines:this.showGridLines
                   };
        }            
    },
	sliderChartDataReady: function(data){
		var d  = this._getDataBySymbol(data,this.mainTicker);
		var cd = this.chartData;
		cd.MiniChartData = d==null||!d.price?null:[d.price.data];
		if(cd.MiniChartData && cd.MiniChartData.length){
			var dd = cd.MiniChartData[0];
        	if(dd&&dd.length&&dd[0]&&dd[0].length)this.slider_StartDate = RTQ_ChartUtil.toDateFromIndex(dd[0][dd[0].length-1]);
		}
		if(this.miniChartFrequency=="minute" && cd.MiniChartData && cd.MiniChartData.length){
			this.rangSize = cd.MiniChartData[0].length-1;
		}else{
			this.rangSize = 512;
		}
		if(this.sliderObj==null){
			this._createSlider();
		}else{
			this.sliderObj.options.max = this.rangSize;
		}
		this.setSliderHandleValues();
		this.drawSliderChart();
	},
	getChartData:function(data,st,ya,cor,w) {
		var isfi = false, fillC = null;
        if(st == "line") return {data:data,lines:{show:true,lineType:"line"},yaxis:ya,color:cor,lineW:w};
		else if(st == "mountain")return {data:data,lines:{show:true,fill:true,fillColor:this.fillColors.pChart,a:0.7},yaxis:ya,color:cor,lineW:w};
		else if(st == "arealine")return {data:data,lines:{show:true,fill:true,fillColor:this.fillColors.pChart,a:0.7},yaxis:ya,color:cor,lineW:w};
        else if (st == "points") return{data:data,points:{show:true},yaxis:ya,color:cor};
        else if (st =="bars") return {data:data,bars:{show:true},yaxis:ya,color:cor};
        else if (st =="candle") return {data:data,candleStick:{show:true},yaxis:ya};
        else if (st =="ohlc" ) return {data:data,OLHC:{show:true,olhcType:"ohlc"},yaxis:ya,color:cor};
		else if (st =="hlc" ) return {data:data,OLHC:{show:true,olhcType:"hlc"},yaxis:ya,color:cor};
        else if (st =="img" ) return {data:data,imagePoints:{show:true},yaxis:ya};
		else if(st=="VBPBar")return{data:data,volumeByPrice:{show:true}};
        else return {data:data,lines:{show:true},yaxis:ya,lineW:w};
    },
	getTicks: function(list,freq) { 
        if(list == null || list.length<1) return null;
		this.xLabelAlign = "left";
        var lg = list.length,dx,temp,vty=0,f=1;
		if(!isNaN(this._frequencyMap[freq])){  // minutely intraday data.
			dx=(list[lg-1][list[lg-1].length-1] - list[0][list[0].length-1])/86400000;
			temp = new Date(list[0][list[0].length-1]);
			f = Math.round(list.length/(dx*0.7));
		}else{
			vty = 1;
			dx = list[lg-1][list[lg-1].length-1] - list[0][list[0].length-1];
			temp = RTQ_ChartUtil.toDateFromIndex(list[0][list[0].length-1]);
		}
        var ty = "d", xx =1;
        var t = [];
        if (dx < 8) {
			ty = "d", t.push([0,QS_DateFmt.getMonthDate(temp)]);
			this.xLabelAlign="center";
        } else if (dx <= 31) {
            ty ="avg",  t.push([0,QS_DateFmt.getMonthDate(temp)]);
			this.xLabelAlign="center";
        } else if (dx <= 61) {
            ty="w",  t.push([0,QS_DateFmt.getMonthDate(temp)]);
        } else if (dx <= 240) {
            ty="m", t.push([0,(temp.getMonth()==0?temp.getFullYear():QS_DateFmt.Mo[temp.getMonth()])]);
			this.xLabelAlign="center";
        } else if (dx <= 730) {
            ty="q";   t.push([0,(temp.getMonth()==0?temp.getFullYear():QS_DateFmt.Mo[temp.getMonth()])]);
        } else if (dx<= 2920) {
            ty ="y",  t.push([0,temp.getFullYear()]);
			this.xLabelAlign="center";
        } else { 
            ty = "5y",  t.push([0,temp.getFullYear()]);
        }
		var wdays = freq=="w"?5:1;// weekly data only fri data.
        for (var i = 1; i < lg;i+= xx) {
            var d = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty);
            if ( ty == "d"||ty == "avg") {
				if(temp.getDate()!=d.getDate()){
					temp = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty);
					t.push([i,QS_DateFmt.getMonthDate(temp)]);
				}           
            }  else if (ty == "w") { 
                if (temp.getDate()!=d.getDate()&&d.getDay() == wdays) {  // weekly data only fri data.
                    temp = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty);
					 t.push([i,QS_DateFmt.getMonthDate(temp)]);
                } 
            } else if (ty == "m") { 
                if (temp.getMonth() != d.getMonth()) { 
                    temp = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty);
					t.push([i,(temp.getMonth()==0?temp.getFullYear():QS_DateFmt.Mo[temp.getMonth()])]);
                }
            } else if (ty == "q") {
                if (((d.getMonth()+1)%3 == 1) && (temp.getMonth() != d.getMonth())) {
                    temp = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty);
					t.push([i,(temp.getMonth()==0?temp.getFullYear():QS_DateFmt.Mo[temp.getMonth()])]);
                } 
            } else if (ty == "y") {
                if (temp.getFullYear() != d.getFullYear()) {
                    temp = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty)
					;t.push([i,temp.getFullYear()]);
                }
            } else { 
                if ((temp.getFullYear() != d.getFullYear()) && (d.getFullYear()%5==0)) {
                    temp = RTQ_ChartUtil.toDateFromIndexOrTick(list[i][list[i].length-1],vty);
					t.push([i,temp.getFullYear()]);
                } 
            }
        } 
        return t;
    },
	 // slider function         
    getSliderStartDate: function() {     //get slider start date.
        if (this.miniChartFrequency == "minute"){
			return this.sDates.lMin;
		}else if (this.miniChartFrequency == "d") {
            return this.sDates.d;
        } else if (this.miniChartFrequency == "w") {
            return this.sDates.w;
        } else if (this.miniChartFrequency == "m") {
            return this.sDates.m;
        } else {
            return new Date(1900,0,1);
        }
    },
	toDate:function(pos) {  // convert the slider position to date.
		var md = this.chartData.MiniChartData;   
        if (pos == 0) {
            return this.slider_StartDate;
        } else { 
            var dx;
            if (this.miniChartFrequency == "m") {
                var dm = this.slider_EndDate.getMonth() - this.slider_StartDate.getMonth() + 1;
                var dy = this.slider_EndDate.getFullYear() - this.slider_StartDate.getFullYear();
                dx = this.rangSize / (dy * 12 + dm);
                var dYear = (this.rangSize - pos) / (12 * dx);
                var ye = Math.floor(dYear);
                var mon = Math.round((dYear - ye) * 12);
                curDate = new Date(this.slider_EndDate.getFullYear() - ye, this.slider_EndDate.getMonth()-mon, 1);
                return curDate;
            } else if (this.miniChartFrequency == "d"||this.miniChartFrequency=="w") {
                var totalTicks = this.slider_EndDate.getTime()- this.slider_StartDate.getTime();
                if (totalTicks == 0) { 
                    return trimDate(this.latestTradeDate); 
                }
                dx = totalTicks * (this.rangSize - pos) / this.rangSize;       
                curDate = new Date (this.slider_EndDate.getTime()-dx);
                return curDate
           } else if(this.miniChartFrequency=="minute"){
		   	  var p = Math.ceil(pos);
		   	  var l = (md[0][1]?md[0][1].length:md[0][0].length)-1;
		   	  var ind = p >= this.rangSize?md[0][this.rangSize][l]:md[0][p][l];
			  return RTQ_ChartUtil.toDateFromIndex(ind);
		   }
        }
    },
	toPos:function(curdate) {  //convert the date to slider postion.
        if (curdate == null) {
            return 0;
        }
		var md = this.chartData.MiniChartData;    
        var pos = 0;
        if (this.miniChartFrequency == "m") {
            var yd = this.slider_EndDate.getFullYear() - curdate.getFullYear();
            var md = this.slider_EndDate.getMonth() - curdate.getMonth();
            var dx = yd * 12 + md;
            var dm = this.slider_EndDate.getMonth() - this.slider_StartDate.getMonth() + 1;
            var dy = this.slider_EndDate.getFullYear() - this.slider_StartDate.getFullYear();
            pos = Math.round(this.rangSize - this.rangSize * dx / (dy * 12 + dm));
        } else if (this.miniChartFrequency == "d" || this.miniChartFrequency == "w") {
            var totalTicks = this.slider_EndDate.getTime()- this.slider_StartDate.getTime();
            var dTicks = this.slider_EndDate.getTime()- curdate.getTime();
            if (totalTicks == 0) {
                return 0;
            }
            pos = Math.ceil(this.rangSize-this.rangSize*dTicks/totalTicks);
        }else if(this.miniChartFrequency=="minute"&&md!=null&&md.length&&md[0]&&md[0].length){
			var d = md[0],lg = (md[0][1]?md[0][1].length:md[0][0].length)-1;
			var ind = RTQ_ChartUtil.toDateIndex(curdate), flag = false;
			for(var i=0;i<d.length;i++){
				if (d[i][lg] >= ind) {
					pos = i,flag=true;
					break;
				}
			}
			if(!flag&&pos==0)pos = d.length-1;  // if date > the maximum of date range.
		}
        if (pos > this.rangSize) {
            return this.rangSize;
        } else if (pos < 0) {
            return 0;
        } else {
            return pos;
        }
    },
	setSliderHandleValues: function() { // reset the slider handlers postion.
        if (this.sliderObj != null) {
			var s = this.toPos(this.startDate),e = this.toPos(this.endDate);
			if(s == e)s--;  // one day;
            this.sliderObj.setOption({values:[s,e]});
        }
		if(this.uiComponents.customDateB != null){
			this.uiComponents.customDateB.setDate(this.startDate,this.endDate);
		}
    },  
	_createSlider: function() { // reset the slider control.
		var self = this;
        if (this._contains.mChartContainer==null||this._contains.mChartContainer.length < 1) return;
        var PosL = this.toPos(this.startDate);
        var PosR = this.toPos(this.endDate);
        if(this.sliderObj == null) {
            this.sliderObj = new Util.Silder(this._contains.mChartContainer[0],{min:0,max:this.rangSize, values:[PosL,PosR]});
            this.sliderObj.onchange = function(v){self.onSliderRangeChanging(v)};
            this.sliderObj.onchanged = function(v){self.onSliderRangeChanged(v)};
        }
    },  
	onSliderRangeChanging: function(values) { // handler the silder changing event
		if(this.isDrawing){
			return false;
		}
		var uiComp = this.uiComponents, el = this._elements;
        if (this.zoomRange != 11) {  // convert to custom
        	if(uiComp.rightMenu != null){
				uiComp.rightMenu.changeUIState(this.frequency,this.zoomRange,false);
				uiComp.rightMenu.changeUIState(this.zoomRange,"zoom",false);
				uiComp.rightMenu.changeUIState(11,"zoom",true);
			}
			if(uiComp.tabZoomMenu!=null){
				uiComp.tabZoomMenu.changeUIState(this.frequency,this.zoomRange,false);
				uiComp.tabZoomMenu.changeUIState(this.zoomRange,null,false);
				uiComp.tabZoomMenu.changeUIState(11,null,true);
				el.tabmenuZoomEl.find(".rtq-ddl-ipt").html("Custom | "+this._frequencyTxtMap[this.frequency]);//this.zoomListData[12].txt+
			}
            this.zoomRange = 11;
            if (uiComp.ddlZoom) {
                uiComp.ddlZoom.setTextValue("Custom", "11");
            }
        }
        var s = this.toDate(values[0]);
        var e = this.toDate(values[1]);
		if(uiComp.customDateB != null){
			uiComp.customDateB.setDate(s,e);
		}
		if(this._elements.legendElm!=null){
			this._elements.legendElm.find(".legend-date").html(RTQ_ChartUtil.formatMDYDate(s)+" - "+RTQ_ChartUtil.formatMDYDate(e));	
		}
    },
	onSliderRangeChanged:function(values) { // loading chart and data when the slider has moved.
	    var s = this.toDate(values[0]);
        var e = this.toDate(values[1]);
        this.startDate = s, this.endDate = e;
		this._clearZoomIn();
        this.zoomRange = 11;
        var  f = this.calculateFrequency(this.startDate);
        this.changeFrequency(f);  
        this.drawChartSegment();
		if(typeof(this.datePeriodChanged) == "function" ){
			this.datePeriodChanged({zoomRange:this.zoomRange,startDate:RTQ_ChartUtil.formatDate(s),endDate:RTQ_ChartUtil.formatDate(e)});
		}
        var ff = this.miniChartFrequency;   // convert minichart view.
        if (values[0] == 0) { 
            ff = this._upMiniFrequency(); //when slider move to the left.
        } else if(this._frequencyIndexMap[f]<= 0){
			ff = "minute";
		} else if (this._frequencyIndexMap[f] > 0&&this._frequencyIndexMap[f] < this._frequencyIndexMap[this.miniChartFrequency]) {
        	ff = f; // zoom in minichart view.
        }
		if(this.noHistoricalData) ff = "minute";
        if (this.miniChartFrequency != ff) {
            this.miniChartFrequency = ff; 
            this.getSilderChartData();
        }
    },
	_getDateRangeString:function(){
		var d = this.chartData.DataList;
		if(!d||!d.length||!d[0]||!d[0].data||!d[0].data.length)return "";
		if(RTQ_ChartUtil.compareDateByday(this.startDate,this.endDate)&&this._frequencyIndexMap[this.frequency]<1){//zoom in one day.
		    var sTick = d[0].data[0][d[0].data[0].length-1],eTick = d[0].data[d[0].data.length-1][d[0].data[d[0].data.length-1].length-1];
			if(this.UIConfig.onedayDateRangeFormat==0){
				return QS_DateFmt.getDateString(new Date(sTick))+"("+QS_DateFmt.getTimeString(new Date(sTick))+"-"+QS_DateFmt.getTimeString(new Date(eTick))+")"+this.timezone;
			}else{
				return RTQ_ChartUtil.formatLegendDate(sTick,this.frequency)+" - "+RTQ_ChartUtil.formatLegendDate(eTick,this.frequency)+" "+this.timezone;
			}
		}else{
			return RTQ_ChartUtil.formatMDYDate(this.startDate)+" - "+RTQ_ChartUtil.formatMDYDate(this.endDate);
		}
	},
	buildLegend:function(item,pos,isMouseout,isDefaut) {
		var el = this._elements, cd = this.chartData;
		if(this.isDrawing){ //jacky remove crosshair
			el.crosshairLegendWin.hide();
			el.lineXElm.hide();
			el.lineYElm.hide();
			return false;
		}
		var timePre="";
		if(this.frequency == "w") timePre = QSLGTXT.week+"&nbsp;"+QSLGTXT.of+"&nbsp;";
		else if(this.frequency == "m")timePre = QSLGTXT.month+"&nbsp;"+QSLGTXT.of+"&nbsp;";
        if ((this.chartCursor == 3 || !this.pChartReady) && !isMouseout) return false;    // chart has not ready ;
        var str="", time = "", vol,volStr="", dataIndex = (isMouseout||item==null||item.dataIndex==null)?-1:item.dataIndex; 
        if (this.chartCursor == 0 || isMouseout) {
            if (dataIndex > 0) {
                time = (item==null)?"--":timePre + RTQ_ChartUtil.formatLegendDate(item.datapoint[item.datapoint.length-1], this.frequency);
                str = '<div class="legend-date">'+time+'</div>'; 
            } else {
                if (this.legendInfo.showDateRangeString) {
                    str = '<div class="legend-date">' + this._getDateRangeString() + '</div>';
                }
            }    
            if(this.showVolume)volStr =" "+QSLGTXT.cvolume+":" + this.getVolInfo(dataIndex);  //get volume infomation
        } else {
            time = (dataIndex < 0 || item.datapoint == null)?"":
				timePre+RTQ_ChartUtil.formatLegendDate(item.datapoint[item.datapoint.length-1],this.frequency);
        }
		// customize callback.
		if(!isMouseout&&typeof(this.chartMouseoverCallback)== "function"&& this.chartCursor == 0 ){//mouse over and chartCursor == 0
			this.chartMouseoverCallback(dataIndex,cd.DataList,cd.VolList,this.startDate,this.endDate);
			if(!isMouseout && item != null && this.zoomRange > 2 && (this.events.dividend || this.events.splits||this.events.earnings)) {
	            this.buildEventLegend(item,false);
	        }
	        if(!isMouseout && item != null && item.dataIndex != null) {
	            this.buildIChartLegend(item.dataIndex);
	        }
			return ;
		} else if(isMouseout&&typeof(this.chartMouseoutCallback)== "function"){ //mouse out
			this.chartMouseoutCallback(-1,cd.DataList,cd.VolList,this.startDate,this.endDate);
			return;
		}
		if (this.chartCursor == 1 && !isMouseout){
			str+= this.createLegendCrosshairRow(-1,null,null,null,time);// add date row;
		}
		if(cd.DataList && cd.DataList.length && cd.DataList.length > 0){   // price chart data.
			var bIsReturn = (this.compairTickers.length > 0 && this.chartStyle!="growth10" && 
				this.chartStyle != "growth" && this.chartStyle != "dEffect")?true:false;
			var lg = cd.DataList.length,d, val,sq, temp,leg,expara;
			for(var i = 0;i < lg;i++){	
			    if(cd.DataList[i].name=="PrevClose") continue;
				leg = cd.DataList[i].legend;
				if (isMouseout) {
					d = cd.DataList[i].data && cd.DataList[i].data.length ? cd.DataList[i].data[cd.DataList[i].data.length-1]:null;
					sq = i;
					if((cd.DataList[i].name == "BBands" ||cd.DataList[i].name == "PChannel"||cd.DataList[i].name == "MAE" ||cd.DataList[i].name == "Keltner")&&
					cd.DataList[i].sq == 0){
						continue;
					}
					if (cd.DataList[i].name == "BBands" ||cd.DataList[i].name == "PChannel"||cd.DataList[i].name == "MAE" ||cd.DataList[i].name == "Keltner") {
						leg = cd.DataList[i].pre;
					}
					if(isDefaut){
						val = d==null||!d.length?"--":this.getReturnValue(d[1],bIsReturn,cd.DataList[i]);
					}else{
						val = "";
					}
					expara="name="+cd.DataList[i].name+" "+"seq="+i;
					if(typeof(cd.DataList[i].sq) != "undefined"){
						expara+=" sq="+cd.DataList[i].sq;
					}
					if(typeof(cd.DataList[i].num) != "undefined"){
						expara+=" num="+cd.DataList[i].num;
					}
				} else {
					if(cd.DataList[i].name=="VBP")continue;
					d = cd.DataList[i].data && cd.DataList[i].data.length && dataIndex < cd.DataList[i].data.length ? 
						cd.DataList[i].data[dataIndex]:null;
					if ((cd.DataList[i].name == "BBands"||cd.DataList[i].name == "PChannel"||cd.DataList[i].name == "MAE" ||cd.DataList[i].name == "Keltner") &&
					cd.DataList[i].sq == 0) {
						temp = d == null ? "--" : this.getPriceValue(d[1], bIsReturn, cd.DataList[i].startPos);
						continue;
					}
					if (i == 0) { // main ticker.
						sq = 0;
						var isMReturn = bIsReturn;//(compairTickers.length > 0) ? true : false;
						if (this.chartCursor == 0) {
							if(this.chartStyle == "growth" ||this.chartStyle == "growth10"||this.chartStyle == "dEffect"||this.chartStyle == "postTax"){
								val = d == null || d.length < 3 ? "--" :this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos);
							}else{
								if(this.legendInfo.OHLC&&!this.legendInfo.onlyIncludeLast){
									val = d == null || d.length < 5 ? "--" : (" "+QSLGTXT.shortopen+":" + this.getPriceValue(d[4], isMReturn, cd.DataList[i].startPos) + 
									" "+QSLGTXT.shorthigh+":" + this.getPriceValue(d[2], isMReturn, cd.DataList[i].startPos) +
									" "+QSLGTXT.shortlow+":" + this.getPriceValue(d[3], isMReturn, cd.DataList[i].startPos) + 
									" "+QSLGTXT.shortclose+":" + (this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos)));
									} else {
									val = d == null || d.length < 2 ?"--":this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos);
								}
							}
							if(this.legendInfo.Volume)val += volStr;
						}else {
							if (this.chartStyle == "growth"||this.chartStyle == "growth10"||this.chartStyle == "dEffect"||this.chartStyle == "postTax") {	
								sq = 1;
								val = [(d == null ? "--" : this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos)),
								this.legendInfo.Volume?this.getVolInfo(dataIndex):""];				
							} else {
								if (this.legendInfo.OHLC) {
									val = d == null || d.length < 5 ? ["--", "--", "--", "--", 
									this.getVolInfo(dataIndex)] : [this.getPriceValue(d[4], isMReturn, 
									cd.DataList[i].startPos), this.getPriceValue(d[2], isMReturn, cd.DataList[i].startPos),
									this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos),
									this.getPriceValue(d[3], isMReturn, cd.DataList[i].startPos), 
									this.getVolInfo(dataIndex)];
								}else {  // fund
									sq = -2;
									val = d == null || d.length < 2 ?["--"]:[this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos)];
								}
							}
						}
					}else {
						sq = 2;
						val = d == null ? "--" : this.getPriceValue(d[1], isMReturn, cd.DataList[i].startPos);
						if (cd.DataList[i].name == "BBands"||cd.DataList[i].name == "PChannel"||cd.DataList[i].name == "MAE" ) {
							val = "U:" + temp + " L:" + val;
							leg = cd.DataList[i].pre;
						} 
						if(cd.DataList[i].name == "Keltner"){
							if(cd.DataList[i].legend!="U"&&cd.DataList[i].legend!="L"){
								leg = cd.DataList[i].pre;
							}else{
								val = "U:" + temp + " L:" + val;
								leg = cd.DataList[i].pre;
							}
						}
					}
				}
				if (this.chartCursor == 0 || isMouseout) { 
		            str+= this.createLegendSpan(sq,leg,val,cd.DataList[i].colorIndex,expara);
		        } else {
		            str+= this.createLegendCrosshairRow(sq,leg,val,cd.DataList[i].colorIndex,time);
		        }
			}
		}
		var stt = "", left,top,lw = this.legendInfo.onlyIncludeLast?130:180;
        if (this.chartCursor == 0||isMouseout) {
			stt = this.buildEventLegend(item,false)
			if (stt != "") {
				el.crosshairLegendElm.html(this.createLegendCrosshairRow(-1,null,null,null,time)+ stt);
				left = pos.pageX-this.chartOffset.left, top = pos.pageY - this.chartOffset.top; 
				if (left+lw > this.chartWidth) {
                	left = left - lw;
        		}
				el.crosshairLegendWin.css({left:left+2,top:top+2}).show();
				
			}else{
				el.crosshairLegendWin.hide();
			}
            if( el.legendElm != null)el.legendElm.html(str);
        } else if(this.chartCursor == 1) { 
			str += this.buildEventLegend(item,true);
            left = pos.pageX - this.chartOffset.left, top = pos.pageY - this.chartOffset.top; 
            el.lineXElm.css({top:top+2});
			el.lineYElm.css({left:left+2});
            if (item != null) {
               el.xLabelElm.html(QS_NumFmt.Fmt2(item.y,true," ",this.precision||2));//item.y.toFixed(this.precision||2)
            }
            el.lineXElm.show(), el.lineYElm.show();
            if (left+lw > this.chartWidth) {
                left = left - lw;
            }
            el.crosshairLegendWin.css({left:left+4,top:top+4}).show();
			el.crosshairLegendElm.html(str)
        }
        if(!isMouseout && item != null && item.dataIndex != null) {
			if(typeof(this.buildVolLegend)!="undefined")this.buildVolLegend(item.dataIndex);
            this.buildIChartLegend(item.dataIndex);
        }else if(isMouseout){
			if(typeof(this.buildVolLegend)!="undefined")this.buildVolLegend(-1);
			this.buildIChartLegend(-1);
		}
    },
	formatIndicatorNum:function(oData,i,index,precision) { 
        if(oData == null || oData.length <= i) return "--"; 
        else if(oData[i]==null||oData[i].data == null||oData[i].data.length <= index) return "--";
        else return (oData[i].data[index] == null || oData[i].data[index].length<=1?"--":QS_NumFmt.Fmt2(oData[i].data[index][1],true," ",precision));
    },
	buildSingleIChartLegend:function(sName,oData,aField,index) {
		var sStr = "";
		var precision = sName =="FVolatility"?3:2;
        for (var i = 0; i < aField.length; i++) {
            sStr+='<span class="rtc-lg-icn'+i+'" style ="color:'+this.tickerColors[i]+'">';
			sStr+=aField[i]+(index==-1?"":(":"+this.formatIndicatorNum(oData,i,index,precision)))+'</span>&nbsp;&nbsp;';
        }
        if(this.iChartContainers[sName])this.iChartContainers[sName].find(".legend").html(sStr);
    },
	buildEventLegend: function(item,hasSymbol) {      
		str="";
        if (item == null ||this.chartData.eventInfoList == null ) {
            return str;
        }  
	    var index = item.dataIndex, isTop = !hasSymbol; 
        var info = [],hasD=false,cls="",dt;
		if((this.events.dividend || this.events.splits||this.events.earnings)&& typeof(this.chartData.eventInfoList[index])!="undefined"){
	        var d = this.chartData.eventInfoList[index];
			if(d.length<1)return"";
			for(var i=d.length-1;i>=0;i--){		
				dt = this.frequency=="w"||this.frequency=="m"?(" | "+RTQ_ChartUtil.formatMDYDate(RTQ_ChartUtil.toDateFromIndex(d[i]["dIndex"]))):"";
				cls = d[i].type==1?"rtc-lg-dividend":(d[i].type==2?"rtc-lg-splits":(d[i].type==3?"rtc-lg-earnings-down":"rtc-lg-earnings-up"));
				str+= '<div class="rtc-legend-row'+(isTop?"-top1":"")+'"><strong class="'+cls+'">'+d[i].name+'</strong><span>'+d[i].val+dt+'</span></div>';
				isTop=false;
			}
        }
		return str;
    },
	buildIChartLegend:function(index){
		var oD,aField;
		for(var o in this.iChartContainers){
			if((this.indicatorsData[o]&& this.indicatorsData[o].show)||(this.valuations&&this.valuations[o]&& this.valuations[o].show)){
				if(o == "MACD"){
					oD  = this.indicatorsData.MACD; 
            		aField = [QSLGIN.macd_lg+"("+oD.parameter[0]+","+oD.parameter[1]+")",QSLGIN.ema_lg+"("+oD.parameter[2]+")",QSLGIN.macd_lg1];
				}else if(o == "RSI"){
					aField = [QSLGIN.rsi_lg+"("+this.indicatorsData.RSI.parameter[0]+")"];
				}else if(o == "ROC"){
					aField = [QSLGIN.roc_lg+"("+this.indicatorsData.ROC.parameter[0]+")"];
				}else if(o == "WillR"){
					aField = [QSLGIN.willr_lg+"("+this.indicatorsData.WillR.parameter[0]+")"];
				}else if(o == "SStochastic"){
					oD  = this.indicatorsData.SStochastic; 
           			aField = [QSLGIN.sstochastic_lg+": %K("+oD.parameter[0]+")","%D("+oD.parameter[1]+")"];
				}else if(o == "FStochastic"){
					oD  = this.indicatorsData.FStochastic; 
            		aField = [QSLGIN.fstochastic_lg+": %K("+oD.parameter[0]+")","%D("+oD.parameter[1]+")"];
				}else if(o=="DMI"){
					aField = [QSLGIN.dmi_lg,QSLGIN.dmi_lg1,QSLGIN.dmi_lg2];
				}else if(o=="ULT"){
					aField = [QSLGIN.ult_lg];
				}else if(o=="Momentum"){
					aField = [QSLGIN.momentum_lg+"("+this.indicatorsData.Momentum.parameter[0]+")"];
				}else if(o=="VAcc"){
					aField = [QSLGIN.vacc_lg];
				}else if(o=="MFI"){
					aField = [QSLGIN.mfi_lg+"("+this.indicatorsData.MFI.parameter[0]+")"];
				}else if(o=="UDRatio"){
					aField = [QSLGIN.udratio_lg+"("+this.indicatorsData.UDRatio.parameter[0]+","+this.indicatorsData.UDRatio.parameter[1]+")"];
				}else if(o=="OBV"){
					aField = [QSLGIN.obv_lg];
				}else if(o=="FVolatility"){
					aField = [QSLGIN.fvolatility_lg];
				}else if(o=="AccDis"){
					aField = [QSLGIN.accdis_lg];
				}else if(o=="Mass"){
					aField = [QSLGIN.mass_lg];
				}else if(o=="Volatility"){
					aField = [QSLGIN.volatility_lg+"("+this.indicatorsData.Volatility.parameter[0]+","+this.indicatorsData.Volatility.parameter[1]+")"];
				} else if (o == "VPlus" || o == "Volume") {
					aField =[this.indicatorUI[this.uiComponents.miniChartRightMenu.owner].title];
					o = this.uiComponents.miniChartRightMenu.owner;
				} else if(o=="ForceIndex"){
					aField = [QSLGIN.forceindex_lg+"("+this.indicatorsData.ForceIndex.parameter[0]+")"];
				}else if(o=="ATR"){
					aField = [QSLGIN.atr_lg];
				}else if(o=="Keltner"){
					aField = [QSLGIN.keltner_lg+"("+this.indicatorsData.Keltner.parameter[0]+","+this.indicatorsData.Keltner.parameter[1]+","+this.indicatorsData.Keltner.parameter[2]+")"];
				} else {
					aField = [this.valuations[o].name + " "];
				}
				this.buildSingleIChartLegend(o,this.iChartData[o],aField,index);
			}
		}
	},
	getVolInfo:function(index) {
		var data = this.chartData;
        var vol = (!data.VolList||!data.VolList.length ||!data.VolList[0].data ||
			index > data.VolList[0].data.length || data.VolList[0].data[index] == null)?NaN: data.VolList[0].data[index][1];
        return QS_NumFmt.Fmt(vol * 1000000, true);
    },
	getPriceValue:function(p,isRt,spos) { 
        var pp= (isRt)?(spos*(100+p)/100):p;
        return QS_NumFmt.Fmt2(pp,true," ",this.precision||2);
    },
	getReturnValue:function(p,isRt,d) { 
        var clo = "", str = "",spos = d.startPos;
		if(spos==null){
			spos = (d!=null && d.data && d.data.length)?d.data[0][1]:NaN;
		}
		if(isNaN(p)&&d.data.length){  // find a  available value
			for(var i=d.data.length-1;i>=0;i--){
				if(d.data[i]&&!isNaN(d.data[i][1])) {
					p = d.data[i][1];
					break;
				}
			}
		}
        if (isNaN(spos)) {
            str = "--";
        } else {  
            var dx = isRt?(spos*p/100):(p-spos); clo = (dx>0)?"green":"red";
            var pp = isRt?p:100*dx/spos;
            str =  isNaN(pp)?"--":QS_NumFmt.Fmt2(dx,true," ",this.precision||2)+"|"+QS_NumFmt.Fmt2(pp,true," ",this.precision||2)+QSLGTXT.percent;
        }
        return "<span style='color:"+clo+"'>"+str+"</span>";
    },
	mouseOutChart:function() {
		var el = this._elements;
        var isDefault = this.UIConfig.chartCtrl =="default"?true:false;
        if (this.chartCursor == 1) {
            el.crosshairLegendWin.hide(); 
            el.lineXElm.hide(); 
			el.lineYElm.hide();
        }
		this.buildLegend(null,null,true,isDefault); 
    },
	clearHighlight: function() {
	    if(this.pFlot != null) {
	        this.pFlot.clearHighlights();
	    }
    },
	chartMouseOut: function() {    
	    var self = this;  
        if(this.mainTicker==""||this.mainTicker==null)return false;
        this.timeout = setTimeout(function(){self.clearHighlight();self.mouseOutChart();},100);
    },
	createLegendSpan: function(sq,name,value,cIndex,extP) {
        var color = cIndex==-1?this.fillColors.vChart:this.tickerColors[cIndex],  v = value ==""?"":":"+value, str="";
		if (sq == 0) {
			str = '<div class = "rtc-main-legend rtc-lg-icn' + cIndex + '" style="color:' + color + '">' + name + v + '</div>';
		}else {
			str = '<div class="rtc-legend"  ' + extP + '><span class = "rtc-lg-icn' + cIndex + '" style="color:' + color + '">'
			str += name + v + '</span></div>';
		}
		return str;
    },
	createLegendCrosshairRow:function(sq,name,value,cIndex,datetime) {
        var str = ""; var cls = sq<2?"rtc-legend-row-top":"rtc-legend-row";
        var claName = "rtc-lg-icn"+cIndex;
        if (sq >= 2) { 
            str+='<div class="rtc-legend-row" ><strong class="'+claName+'">'+name+':</strong><span>'+value+'</span></div>';
        } else if(sq == 0){  // ETF
            if(this.legendInfo.onlyIncludeLast){ // only show close price.
                str+= '<div class="'+cls+'"><strong class="'+claName+'">'+name+'</strong><span>'+QSLGTXT.close+':'+value[2]+'</span></div>';
                if(this.showVolume){
                    str+='<div class="rtc-legend-row-top" ><span>&nbsp;&nbsp;'+QSLGTXT.cvolume+':</span><span>'+value[4]+'</span></div>'
                }
            }else{
                str+= '<div class="'+cls+'"><strong class="'+claName+'">'+name+'</strong></div>';
                str+= '<div  class="rtc-legend-table"><table cellpadding="0" cellspacing="0">';
                str+='<tr><td><span class="left">'+QSLGTXT.open+':</span><span class="right">'+value[0]+'</span></td><td class="td-mid">&nbsp;</td>';
                str+='<td><span class="left">'+QSLGTXT.high+':</span><span class="right">'+value[1]+'</span></td></tr>';
                str+='<tr><td><span class="left">'+QSLGTXT.close+':</span><span class="right">'+value[2]+'</span></td><td class="td-mid">&nbsp;</td>';
                str+='<td><span class="left">'+QSLGTXT.low+':</span><span class="right">'+value[3]+'</span></td></tr>';
                if(this.showVolume) str+='<tr><td style="border-bottom:0" colspan="3"><span class="left">'+QSLGTXT.cvolume+':</span><span class="right">'+value[4]+'</span></td></tr>';
            }
			
            str+='</table></div>';                
        }else if(sq == -2){  // fund
			str+= '<div class="'+cls+'"><strong class="'+claName+'">'+name+'</strong></div>';
			str+= '<div  class="rtc-legend-table"><table cellpadding="0" cellspacing="0">';
			str+='<tr><td>';
			str+='<span class="left">'+QSLGTXT.nav+':</span><span class="right">'+value[0]+'</span></td></tr></table></div>';    
		} else if (sq == 1) {
			var pname = this.chartStyle=="growth"||this.chartStyle == "dEffect"?QSLGTXT.pergrowth:QSLGTXT.price;
			if(this.chartStyle=="growth10")pname=QSLGTXT.tenkgrowth;
            else if(this.chartStyle=="postTax")pname=QSLGTXT.posttaxreturn;
            str+= '<div class="'+cls+'"><strong class="'+claName+'">'+name+'</strong></div>';
			str+='<div  class="rtc-legend-table"><table cellpadding="0" cellspacing="0"><tr><td><span class="left">';
            str+= pname+':</span><span class="right">'+value[0]+'</span></td></tr>';
			if(value[1]&&value[1]!=""){
				str+='<tr><td style="border-bottom:0"><span class="left">'+QSLGTXT.cvolume+':</span><span class="right">'+value[1]+'</span></td></tr>';
			}
			str+='</table></div>';
			                
        } else if(sq == -1) {
			str+= '<div class="rtc-legend-row-date"><strong>'+datetime+'</strong></div>';
		}      
        return str;        
    },
	legendOnClick: function(elm){   // legend onclick handler.
		var name = elm.attr("name"),seq = elm.attr("seq"), sq = elm.attr("sq"), num = elm.attr("num");
		var  el = this._elements;
		if(name!="MReturnIndex") elm.remove();
		var needChangeUi = false;
		if(name=="SMA"||name=="EMA"){
			needChangeUi = this.removeIndicators(name,num);
		} else if(name =="BBands" || name == "PSAR"||name == "PChannel" || name == "MAE" || name=="VBP"||name=="WMA"||name=="Keltner"){
			needChangeUi = this.removeIndicators(name);
		} else if(name == "SMAV"){
			needChangeUi = this.removeIndicators(name);
		} else if (name=="FairValue"){  // valuation
			this.removeValuations(name);
			el.valuationULElm.find("a[value='"+name+"']").addClass("rtq-chkbox_off");
			this.changeRightMenuClass(2,name,false);
		}else if(name == "_iiv"){
			this.switchIIV(false);
            if(typeof(this.afterSwitchIIV)=="function")this.afterSwitchIIV({showIIVTicker:this.showIIVTicker});
			if(this.uiComponents.chkIIV!=null)this.uiComponents.chkIIV.btns['showIIV'].inverse()
		} else {
			this.removeCompairTicker(name);
			if(this.indexsMap&&this.indexsMap[name]){
				this.indexsMap[name].show = false;
				el.indexsULElm.find("a[value='"+name+"']").addClass("rtq-chkbox_off");
			}
			if(el.relatedSecULElm)el.relatedSecULElm.find("a[value='"+name+"']").addClass("rtq-chkbox_off");
		}
		if(needChangeUi){  // change check box state to false.
			el.indicatorULElm.find("a[value='"+name+"']").addClass("rtq-chkbox_off");
			this.changeRightMenuClass(2,name,false);
			this.changeRightMenuClass(2, "SMAV", false);
		}
		if(this.UIConfig.chartCtrl=="default"&&name=="SMA"&&el.m1!=null){
			sq==0?el.m1.val(""):sq==1?el.m2.val(""):el.m3.val("");
		}
	},
	iChartLegendOnclick:function(name){
		var el = this._elements;
		var ty = this.removeIChart(name);
		if(ty!=null){
			if(ty == "indicator"){
				el.indicatorULElm.find("a[value='"+name+"']").addClass("rtq-chkbox_off");
				this.changeRightMenuClass(2,name,false);
				if(typeof(this.afterRemoveIndicators)== "function"){  // after callback;
                    this.afterRemoveIndicators({indicatorName:name,paras:null});
                }
			}else if(ty=="fundamental"){
				el.valuationULElm.find("a[value='"+name+"']").addClass("rtq-chkbox_off");
				this.changeRightMenuClass(2,name,false);
				if(typeof(this.afterRemoveValuationCallback)=="function"){
					this.afterRemoveValuationCallback({name:name});
				}
			}
		}
	},
	removeIChart: function(sName){ //remove indicator or valuation chart.
    	var removeType = null;
		if (this.iChartContainers[sName]) { // hide the new indicator chart
			this.iChartContainers[sName].hide();
			if(this.UIConfig.autoHeight) {
			   this.outHeight -= this.iChartHeight;    //
			}
        }
		if(this.indicatorsData.hasOwnProperty(sName)){
			if(this.indicatorsData[sName].show){
				this.indicatorsData[sName].show = false;
				removeType = "indicator";
			}
		}else {
			this.valuations[sName].show = false;
			removeType = "fundamental";
		}     
		this.iChartData[sName] = [];
        this.changeOutSize(this.chartWidth,this.outHeight);
		return removeType;
	},
	_removeDataRowFromDataList:function(symbol,sq){
		if(!this.chartData.DataList.length)return;
		for(var i = 0; i < this.chartData.DataList.length;i++){
			if(this.chartData.DataList[i].name == symbol){
				if((this.chartData.DataList[i].sq == sq) ||typeof(sq)== "undefined"){
					this.chartData.DataList.splice(i,1);
					i--;
				}	
			}
		}
	},
	changeRightMenuClass:function(ty,name,tf){
		var uiComp = this.uiComponents;
		if(uiComp.rightMenu!=null){
			uiComp.rightMenu.changeItemClass(name,null,"rtq-menu-on",tf);
		}
		if(typeof(uiComp.miniChartRightMenu.menu)!="undefined" && uiComp.miniChartRightMenu.menu!=null){
			uiComp.miniChartRightMenu.menu.changeItemClass(name,null,"rtq-menu-on",tf);
		}
	},
	removeIndicatorClicked:function(obj) { 
		var el = this._elements; 
        var sName = this._selectedIndicatorName;
        el.indicatorWinElm.hide();
        var needChangeUi = this.removeIndicators(sName);
		if(needChangeUi){  // change check box state to false.
			el.indicatorULElm.find("a[value='"+sName+"']").addClass("rtq-chkbox_off");
			if(this.UIConfig.RightMenu){
				this.changeRightMenuClass(0,sName,false);
			}
			if(sName=="Volume"){
				el.indicatorULElm.find("a[value='VPlus']").addClass("rtq-chkbox_off");
				el.indicatorULElm.find("a[value='SMAV']").addClass("rtq-chkbox_off");
			}else if(sName=="VPlus"){
				el.indicatorULElm.find("a[value='Volume']").addClass("rtq-chkbox_off");
				el.indicatorULElm.find("a[value='SMAV']").addClass("rtq-chkbox_off");
			}
		}
    },
	checkCompairTicker: function(t) {
        if (t.toUpperCase() == this.mainTicker.toUpperCase()) {
            return true;
        }
    	for (var i = 0; i < this.compairTickers.length; i++) {
    	    if (this.compairTickers[i].toUpperCase() == t.toUpperCase()) {
    	        return true;
    	    }
        }
        return false;
    },
	bacthUnscribeTickers:function(pids){
		if(typeof(this.tValidation)== "object" && typeof(gIdMap)== "object"){ // QSII terminal
			this.tValidation.unSubscribe(pids);
		}else{
			//unsubscribeStock(pids);
		}
	},
	_getIChartType: function(name){
		if(this.valuations&&typeof(this.valuations[name])!="undefined"){
			return "va";   //valuation
		}else if(this.indicatorsData&&typeof(this.indicatorsData[name])!="undefined"){
			return "in";   //indicator
		}
		return "button";
	},
	preSwitchIChart: function(){
		var iwin = this.ichartSiwtchIndicatorWin;
		var flag = this.switchIChart(iwin.oldName,iwin.newName);
		var oldType = this._getIChartType(iwin.oldName), newType = this._getIChartType(iwin.newName);
		iwin.data.el.addClass("rtq-menu-on");
		if(flag){
			this.changeRightMenuClass(2,iwin.oldName,false);
			this.changeRightMenuClass(2,iwin.newName,true);
			var oEl = oldType=="in"?this._elements.indicatorULElm:this._elements.valuationULElm;
			var nEl = newType=="in"?this._elements.indicatorULElm:this._elements.valuationULElm;
			oEl.find("a[value='"+iwin.oldName+"']").addClass("rtq-chkbox_off");   // change the setting panel intem's status.
			nEl.find("a[value='"+iwin.newName+"']").removeClass("rtq-chkbox_off");
		}
		iwin.flag = false;
	},
	switchIChart: function(oldName,name){  // 
		var oldType = this._getIChartType(oldName), newType = this._getIChartType(name);
		var temp = this.iChartContainers[name];
		this.iChartContainers[name] = this.iChartContainers[oldName];
		this.iChartContainers[oldName] = temp;
		if (typeof(this.iChartContainers[oldName]) != "undefined" && this.iChartContainers[oldName] != null) {
			this.iChartContainers[oldName].attr("name", oldName);
		}
		var temp2 = this.iFlots[name];
		this.iFlots[name]= this.iFlots[oldName];
		this.iFlots[oldName] = temp2;
		if(oldType=="in"){
			this.indicatorsData[oldName].show = false;
		}else if(oldType=="va"){
			this.valuations[oldName].show = false;
		}
		if(newType=="in"){
			//this.addIndicators(name);
		}else if(newType=="va"){
			this.addValuations(name);
		}	
		return true;	
	},
	_onIchartMenuItemClicked:function(idx,data){  // callback for mini-chart right menu items are clicked 
		var oldName = this.uiComponents.miniChartRightMenu.owner, name = data.data.val;
		var oldType = this._getIChartType(oldName), newType = this._getIChartType(name);
		if(name == "edit" && newType == "button"){        //edit button 
			if (oldType == "in" && this.indicatorsData[oldName].show) {
				if (this.indicatorUI[oldName].parameter.length > 0) {
					this.showIndicatorWin(oldName);
				}
			}
		}else{
			if(oldType!="button"||newType!="button"){
				if(newType=="in"&&this.indicatorsData[name].show){ // indicator chart.
					if(this.indicatorUI[name].parameter.length > 0){
						this.showIndicatorWin(name);
					}else{
						return false;
					}
				}
				if(newType=="va" && this.valuations[name].show){ // valuation chart.
					return false;
				}
			}	
		}
		var flag = false;
		if(newType=="in"){
			this.ichartSiwtchIndicatorWin = {flag:true,oldName:oldName,newName:name,data:data};
			if(this.indicatorUI[name].parameter.length == 0){
				this.preSwitchIChart();
			}
			this.showIndicatorWin(name);
		}else if(newType == "va")	{
			this.ichartSiwtchIndicatorWin = {flag:true,oldName:oldName,newName:name,data:data};
			this.preSwitchIChart();
		}
		if(this.uiComponents.miniChartRightMenu.menu!=null)this.uiComponents.miniChartRightMenu.menu.hide();	
	},
    acceptTicker: function(symbol)  { // change ticker interface.
	    if (symbol != null && symbol !="") {
	        this.validateMainTicker(symbol);
	    }
    },
    checkTickerInfo:function(symbol,callback) {
        if (symbol == "") {
            return false;
        }    
        var url = this.dataUrl.getTickerInfoURL + "symbol=" + symbol;// + "&cb="+callback;
        $.getJSON(url+"&cb=?",callback);
    },
	// validate the tikcers in chart.
    validateSavedTickers:function(symbol){
        if(typeof(this.tValidation)=="object" && typeof(gIdMap)!= "undefined"&&typeof(gData)!="undefined"){//QSII terminal
            var self = this;
            this.tValidation.checkTickers(symbol,function(o){
                var pid,stype,symbols=[];
                self.compairTickers = [];
                if(o && o.length > 0){
                    for(var i = 0;i < o.length;i++){
						//mainTicker
                        //pid = gData[o[i]]["performanceId"];
                        stype = gData[o[i]]["mType"];
                        pid = gData[o[i]]["type"]==8?gData[o[i]]["secId"]:gData[o[i]]["performanceId"];
                        var info = gData[o[i]];
                        info.gkey=o[i];
                        GB_ChartDataManager.registerSymbol(info);
                        if(!self.tickerInfos[pid]){
                            self.tickerInfos[pid] = {exch:gData[o[i]]["exch"],ticker:gData[o[i]]["ticker"],clientTicker:gData[o[i]]["clientTicker"],gkey:o[i],mType:stype};
                        }
                        if(i==0){
                            self.mainTicker = pid;
                            GB_ChartDataManager.registerChart(pid,self.id);
                            if (self.sType != stype) {
                                self._securityTypeChanged(self.sType, stype);
                                self._toggleFundamentalItem(self.sType,stype);
                            }
                            self._filterFrequencyMenuData(gData[o[i]],true);
							self.noHistoricalData = gData[o[i]]["noPID"];
                            self.sType = stype;
                            if(stype == "FE"){ // subject ticker is ETF ticker.
                                self.iivTicker = pid+"IIV";
                                if (gIdMap[self.iivTicker]) {
                                    GB_ChartDataManager.registerSymbol(gData[gIdMap[self.iivTicker]]);
                                    self.tickerInfos[self.iivTicker] = {
                                        exch: gData[gIdMap[self.iivTicker]]["exch"],
                                        ticker: gData[gIdMap[self.iivTicker]]["ticker"],
                                        clientTicker:gData[gIdMap[self.iivTicker]]["clientTicker"],
                                        gkey: gData[gIdMap[self.iivTicker]]["gkey"]
                                    };
                                    if (self._elements.iivContainer) 
                                        self._elements.iivContainer.show();
                                }else{
                                    self.iivTicker = "";
                                }
                            }else{
                                if(self._elements.iivContainer)self._elements.iivContainer.hide();
                            }
                        }else {
                            self.compairTickers.push(pid);
                            symbols.push(self.tickerInfos[pid]);
                        }     
                    }
                    self.initComponent();   
                    if(typeof(self.afterAcceptTickers) == "function"){
                        self.afterAcceptTickers({mainTicker:self.tickerInfos[self.mainTicker]});
                    }
                    if(typeof(self.afterAddTickers) == "function"&&symbols.length){
                        self.afterAddTickers({symbol:symbols});
                    }
                }
            });
        } else {
            for(var i=0;i < symbol.length;i++){
                if(i!=0 && this.tickerInfos[symbol[i]]){
                    GB_ChartDataManager.registerSymbol(this.tickerInfos[symbol[i]]);  // regesiter compare tickers.
                }
            }
			this.mainTicker = "";
            var self = this;
			this.checkTickerInfo(symbol[0],function(d){
                self.onMainTickerChanged(d);
            }); // check main ticker
        }   
    },
	
	//fixed: no intraday data,2011.8.22
	_filterFrequencyMenuData:function(d,needDefaultCfg){
        var tempMenuCfg = {};
        if(needDefaultCfg){
            tempMenuCfg = $.extend(tempMenuCfg,this.defaultFrequencyMenuCfg);
        }
        if (!d.tenforeTicker||(typeof(mockExchangeCode)!="undefined"&&d.tenforeCode==mockExchangeCode)) {
            tempMenuCfg.intraday = false;
        }
        if ((!d["secId"] && !d["performanceId"]) || d["noPID"]) {
            tempMenuCfg.history = false;
        }
		if(d["type"]=="FO"){
			tempMenuCfg.intraday=false;
		}
        this.reBindFrequencyMenuData(tempMenuCfg,needDefaultCfg);
	},
	   /**
     * 
     * @param {string} type (type=[intraday|history|all])
     */
    reBindFrequencyMenuData:function(cfg,needDefaultCfg){//{intraday:true,histoay:true,customer:true}
       var tempCfg =$.extend({intraday:true,history:true,customer:true},cfg);

        var flag = false;
        for(var i in this.requencyMenuCfg){
            if(this.requencyMenuCfg[i]!==tempCfg[i]){
                flag = true;
            }
        }
        if(!flag&&typeof(needDefaultCfg)=="undefined"){
            return;
        }
        this.requencyMenuCfg=tempCfg;
        var arr = this._getZoomListData(tempCfg.intraday,tempCfg.history,tempCfg.customer);
        //this.zoomListData=arr;
        if (this.uiComponents.tabZoomMenu!=null)this.uiComponents.tabZoomMenu.reBind(arr);
        if(this.uiComponents.ddlZoom!=null)this.uiComponents.ddlZoom.rebindData(arr);
        //this.uiComponents.rightMenu.reBind(this.rightMenuData);
        if(this.uiComponents.rightMenu!=null) this.uiComponents.rightMenu.reBindSecondLevelMenu("zoom",arr,1);
        if (this.uiComponents.ddlZoom != null) {
            this.uiComponents.ddlZoom.setTextValue(null, this.zoomRange);
        }
		if(typeof(this.afterZoomMenuRebind)=="function"){
			this.afterZoomMenuRebind(arr);
		}
    },
	_getZoomListData:function(hasIntraday,hasHistory,hasCustom){
        var arr=[];
        if(hasIntraday&&!hasHistory){// only intraday data
            this.sMinuteFreMenuData.splice(4,1);
            this.lMinuteFreMenuData.splice(2,2);
        }
        if(hasIntraday){
            arr=arr.concat([{txt:"1 "+QSLGTXT.shortday,val:"1",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.intradayFreMenuData},
            {txt:"5 "+QSLGTXT.shortday,val:"2",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.intradayFreMenuData},
            {txt:"15 "+QSLGTXT.shortday,val:"13",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.sMinuteFreMenuData}]);
        }
        if (hasIntraday || hasHistory) {
            arr = arr.concat([{
                txt: "1 " + QSLGTXT.shortmonth,
                val: "3",
                type: "ratio",
                catekey: "zoom",
                selectable: false,
                subMenu: (hasIntraday ? this.sMinuteFreMenuData : this.dailyFreMenuData)
            }, {
                txt: "2 " + QSLGTXT.shortmonth,
                val: "14",
                type: "ratio",
                catekey: "zoom",
                selectable: false,
                subMenu: (hasIntraday ? this.lMinuteFreMenuData : this.dailyFreMenuData)
            }, {
                txt: "3 " + QSLGTXT.shortmonth,
                val: "4",
                type: "ratio",
                catekey: "zoom",
                selectable: false,
                subMenu: (hasIntraday ? this.lMinuteFreMenuData : this.dailyFreMenuData)
            }]);
        }
        if(hasHistory){
            arr = arr.concat([
            {txt:QSLGTXT.ytd,val:"5",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
            {txt:"1 "+QSLGTXT.shortyear,val:"6",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
            {txt:"3 "+QSLGTXT.shortyear,val:"7",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
            {txt:"5 "+QSLGTXT.shortyear,val:"8",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
            {txt:"10 "+QSLGTXT.shortyear,val:"9",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.dailyFreMenuData},
            {txt:QSLGTXT.max,val:"10",type: "ratio",catekey:"zoom",selectable: false,subMenu:this.monthlyFreMenuData}]);
        }
        if(hasCustom){
            arr = arr.concat([{txt:QSLGTXT.custom,val:"11",type: "ratio"}]);
        }
        return arr;
    },
	validateMainTicker:function(symbol){  
        if(typeof(this.tValidation)=="object" && typeof(gIdMap)!= "undefined"&&typeof(gData)!="undefined"){//QSII terminal
            var self = this;
            this.tValidation.checkTickers(symbol,function(o){
                if (typeof(self.hideLoading) == 'function' && typeof(o) != 'undefined' && o.length == 0) {
                    self.hideLoading();
                }
                if(o && o.length > 0){
                    var ty = gData[o[0]]["type"];
                    var stype = gData[o[0]]["mType"];
					var id = ty==8?gData[o[0]]["secId"]:gData[o[0]]["performanceId"]; // fund use secId as key.
                    if($.inArray(parseInt(ty),self.securityType)== -1||self.mainTicker == id){  // invaild type or the ticker is same with current subject ticker.
                        return;
                    }
                    if(self.mainTicker != ""){  // clear the old subject ticker.
                        GB_ChartDataManager.unregisterSymbol(self.mainTicker);
                        GB_ChartDataManager.unregisterChart(self.mainTicker,self.id);
                        self.bacthUnscribeTickers([self.mainTicker]);
                        delete self.tickerInfos[self.mainTicker];
                    }
                    self.mainTicker = id;
                    self.tickerInfos[self.mainTicker]={exch:gData[o[0]]["exch"],ticker:gData[o[0]]["ticker"],clientTicker:gData[o[0]]["clientTicker"],gkey:o[0],mType:stype};
                    var info = gData[o[0]],flag = false;
                    info.gkey=o[0];
                    for (var i = 0; i < self.compairTickers.length; i++) {  
                        if (self.mainTicker == self.compairTickers[i]) {  // main ticker is in compair tickers.
                            self.compairTickers.splice(i,1);
                            flag = true;
                            break;
                        }
                    }
                    if(!flag){
                        GB_ChartDataManager.registerSymbol(info);
                    }
                    if (self.sType != stype) {
                        self._securityTypeChanged(self.sType, stype);
                        self._toggleFundamentalItem(self.sType,stype);
                    }
                    self._filterFrequencyMenuData(gData[o[0]],true);
					self.noHistoricalData = gData[o[0]]["noPID"];
                    self.sType = stype;
                    if(stype == "FE"){ // subject ticker is ETF ticker.
                        self.iivTicker = id+"IIV";
                        if (gIdMap[self.iivTicker]) {
                            GB_ChartDataManager.registerSymbol(gData[gIdMap[self.iivTicker]]);
                            self.tickerInfos[self.iivTicker] = {
                                exch: gData[gIdMap[self.iivTicker]]["exch"],
                                ticker: gData[gIdMap[self.iivTicker]]["ticker"],
                                clientTicker: gData[gIdMap[self.iivTicker]]["clientTicker"],
                                gkey: gData[gIdMap[self.iivTicker]]["gkey"]
                            };
                        }else{
                            self.iivTicker = "";
                        }
                        if(self._elements.iivContainer)self._elements.iivContainer.show();
                    }else{
                        if(self._elements.iivContainer)self._elements.iivContainer.hide();
                    }   
                    GB_ChartDataManager.registerChart(self.mainTicker,self.id);
                    self.initComponent();
                    if(typeof(self.afterAcceptTickers) == "function"){
                        self.afterAcceptTickers({mainTicker:self.tickerInfos[self.mainTicker]});
                    }
                }
            });
        } else {
            var self = this;
            this.checkTickerInfo(symbol,function(d){
                self.onMainTickerChanged(d);
            });
        }   
    },
	validateCompairTicker:function(symbol){
        var self = this;
        if(typeof(this.tValidation)=="object" && typeof(gIdMap)!= "undefined"&&typeof(gData)!="undefined"){  //QSII terminal
            this.tValidation.checkTickers(symbol,function(o){
				if (typeof(self.hideLoading) == 'function' && typeof(o) != 'undefined' && o.length == 0) {
                    self.hideLoading();
                }
                if(o && o.length > 0){
                    var flag = false,pid,symbols=[];
                    for(var i = 0;i<o.length; i++){
                        var ty = gData[o[i]]["type"];
                        pid = ty==8?gData[o[i]]["secId"]:gData[o[i]]["performanceId"];
                        if(!pid || pid=="" || self.checkCompairTicker(pid)){//(ty!=1&&ty!=10)||
                            continue;
                        }
                        if (self.compairTickers.length >= self.tickerMaxNum) {
                            if (self.hasConfirmBox) {
                                Util.message(TEXT?TEXT.ChartCTickersOverstep:"The maximum compair tickers are reached.");
                            }
                            break;
                        }       
                        self.compairTickers.push(pid) ;
                        self.tickerInfos[pid]={exch:gData[o[i]]["exch"],ticker:gData[o[i]]["ticker"],clientTicker:gData[o[i]]["clientTicker"],gkey:o[i]};
                        symbols.push(self.tickerInfos[pid]);
                        flag = true;
                        var info = gData[o[i]];
                        info.gkey=o[i];
                        GB_ChartDataManager.registerSymbol(info);
                    }
                    if(flag){
                        self.getPChartData();
                    }
                    if(typeof(self.afterAddTickers) == "function"){
                        self.afterAddTickers({symbol:symbols});
                    }
                }else{
                    if(self.indexsMap&&self.indexsMap[symbol])self.indexsMap[symbol].show = false;
                    if(self._elements.indexsULElm)self._elements.indexsULElm.find("a[value='"+symbol+"']").addClass("rtq-chkbox_off");
                    if(self._elements.relatedSecULElm) self._elements.relatedSecULElm.find("a[value='"+symbol+"']").addClass("rtq-chkbox_off");
                    setTimeout(function(){
                        Util.message(TEXT?TEXT.ChartCTickersNoEntitled:'You are not entitled to access this security.');
                    },10);
                }
            });
        } else {
            this.checkTickerInfo(symbol,function(d){
                self.onCompareTickerAdded(d);
            });
        }
    },
	onMainTickerChanged: function(data)  {   // handler change main ticker.
        if (data == null || data.Records == null || !data.Records.length) {
            return;
        }
        var tickerList = data.Records;
		var id = this._securityTypeMap[tickerList[0].Type]== 8?tickerList[0].SID:tickerList[0].PID;  // Mutual Fund use SID as key.
        if (id!= "" && id != this.mainTicker) { // use performanceId as ticker key.
            if(this.mainTicker != ""){
				GB_ChartDataManager.unregisterChart(this.mainTicker,this.id);  // unregister chart.
                GB_ChartDataManager.unregisterSymbol(this.mainTicker);
                this.bacthUnscribeTickers([this.mainTicker]);
                delete this.tickerInfos[this.mainTicker];
            }
            this.mainTicker = id;
            this.tickerInfos[this.mainTicker]= {};
            this.storeTickerInfo(this.tickerInfos[this.mainTicker],tickerList[0]);  // store ticker information.
            var flag = false;
            if(this.sType != tickerList[0].Type)this._securityTypeChanged(this.sType,tickerList[0].Type);
            this.sType = tickerList[0].Type; 
            for (var i = 0; i < this.compairTickers.length; i++) {
                if (this.mainTicker == this.compairTickers[i]) {  // main ticker is in compair tickers.
                    this.compairTickers.splice(i,1);
                    flag = true;
                    break;
                }
            }
            if(!flag){
                GB_ChartDataManager.registerSymbol(this.tickerInfos[this.mainTicker]);
                if(this.sType == "FE"){  // ETF and has IIV ticker.
                	this.iivTicker = this.mainTicker+"IIV";
            		if(this.tickerInfos[this.iivTicker]){
	                    GB_ChartDataManager.registerSymbol(this.tickerInfos[this.iivTicker]);
						if(this._elements.iivContainer)this._elements.iivContainer.show();
					}else{  // no iiv ticker.
						this.iivTicker = "";
						if(this._elements.iivContainer)this._elements.iivContainer.hide();
					}
                   
                }else{
					if(this._elements.iivContainer)this._elements.iivContainer.hide();
				}
            } 
			GB_ChartDataManager.registerChart(this.mainTicker,this.id);			
            this.initComponent();
        } 
        if(typeof(this.afterAcceptTickers) == "function"){
            this.afterAcceptTickers({mainTicker:this.tickerInfos[this.mainTicker]});
        }
    },
	onCompareTickerAdded: function (data) {   // add compair tickers.
        if (data == null || data.Records == null || data.Records.length == 0) {
            return;
        }
        var tickerList = data.Records;
        var flag = false;
        var symbols =[], needSubscribe = [];
        for (var i = 0; i < tickerList.length; i++) {
            var ticker = tickerList[i]; 
			var id = this._securityTypeMap[ticker.Type]== 8?ticker.SID:ticker.PID;  // Mutual Fund use SID as key.
            if (id == ""|| this.checkCompairTicker(id)) {
                if (id == ""&& this.hasConfirmBox) {
                    Util.message('We could not find the security["{'+ticker.Ticker+'}"] you are looking for. Please try again.');
                }
                continue;
            } else {
                if (this.compairTickers.length >= this.tickerMaxNum) {
                    if (this.hasConfirmBox) {
                        Util.message("The maximum compair tickers are reached.");            
                    } 
                   break;
                }   
                this.compairTickers.push(id);
                this.tickerInfos[id] = {};
                this.storeTickerInfo(this.tickerInfos[id],tickerList[i]);   
                GB_ChartDataManager.registerSymbol(this.tickerInfos[id]);
                flag = true;
                symbols.push(this.tickerInfos[id]);
                if(this.indexsMap&&this.indexsMap[id]&& this.indexsMap[id].show){
                    this._elements.indexsULElm.find("a[value='"+id+"']").removeClass("rtq-chkbox_off");
                }
            }
        }
        if(typeof(this.afterAddTickers) == "function"){
            this.afterAddTickers({symbol:symbols});
        }
        if (flag) { // add a symbol
            this.getPChartData();
        }   
        
    },
    _toggleFundamentalItem:function(otype,stype){
        if(stype=="FE"||stype=="XI"||stype=="FC"){ // hide the fundamental for index,etf and CE
            if(otype!="FE"&&otype!="XI"&&otype!="FC"){
                if(this._contains.$settingPanel!=null)this._contains.$settingPanel.find(".rtq-groupbox-group").eq(6).hide();
                for(var ii in this.iChartContainers){
                    if(this.valuations.hasOwnProperty(ii)){
                        this.iChartLegendOnclick(ii);
                    }
                }
				if(this.valuations.FairValue&&this.valuations.FairValue.show){
					this.removeValuations("FairValue");
				}
                var tempArr = [];
                for(var k = 0;k<this.rightMenuData.length;k++){
                    if(this.rightMenuData[k].val!="mainl1-fundamental"&&this.rightMenuData[k].val!="mainl1-valuation"){
                        tempArr.push(this.rightMenuData[k]);
                    }
                }
                if(this.uiComponents.rightMenu!=null)this.uiComponents.rightMenu.reBind(tempArr);
                tempArr=[];
                for(var k = 0;k<this.miniChartRightMenuData.length;k++){
                    if(this.miniChartRightMenuData[k].val!="minil1-fundamental"&&this.miniChartRightMenuData[k].val!="minil1-valuation"){
                        tempArr.push(this.miniChartRightMenuData[k]);
                    }
                }
                if(this.uiComponents.miniChartRightMenu.menu!=null)this.uiComponents.miniChartRightMenu.menu.reBind(tempArr);
            }     
        }else {  
            if(this._contains.$settingPanel!=null)this._contains.$settingPanel.find(".rtq-groupbox-group").eq(6).show();
            if(this.uiComponents.rightMenu!=null) this.uiComponents.rightMenu.reBind(this.rightMenuData);
        }
    },
    _securityTypeChanged:function(oty,ty){  // ETF switch to Stock and Close-end Fund, or Stock and Close-end Fund switch to ETF.
        if((oty=="ST"||oty=="FC")&& ty=="FE"){  // show the post-tax type.
            var flag = false;
            for(var i=0; i< this.chartTypeListData.length;i++){
                if(this.chartTypeListData[i].val == "postTax"){  // 
                    flag = true;
                    break;
                }
            }
           if(!flag){  //
               this.chartTypeListData.push({txt:QSLGTXT.posttaxreturn,type:"ratio",val:"postTax"});
               if(this.chartTypeMenuData.length>=4){
                   this.chartTypeMenuData[3].push({txt:QSLGTXT.posttaxreturn,type:"ratio",val:"postTax"});       
               }
                this._rebindTypeList();
           }             
        }else if(oty=="FE"&&(ty=="ST"||ty=="FC")){  // hide the post-tax type;
            var flag = false;
            for(var i=0; i< this.chartTypeListData.length;i++){
                if(this.chartTypeListData[i].val == "postTax"){  // 
                    flag = true;
                    this.chartTypeListData.splice(i,1);
                    break;
                }
            }
            if(flag){  // remove the "post tax return" type.
               if(this.chartStyle == "postTax") this.chartStyle = "mountain";
               if (this.chartTypeMenuData.length >= 4) {
                    for(var j=0;j< this.chartTypeMenuData[3].length;j++){
                        if(this.chartTypeMenuData[3][j].val=="postTax"){
                            this.chartTypeMenuData[3].splice(j,1);
                            break;
                        }
                    }
               }
               this._rebindTypeList();
            }
        }
    },
    _rebindTypeList:function(){
        if(this.uiComponents.ddlChartType!=null){  // rebind chart type DDL.
           this.uiComponents.ddlChartType.rebindData(this.chartTypeListData);
        }
        if(this.uiComponents.rightMenu != null){
            this.uiComponents.rightMenu.reBindSecondLevelMenu("chartType",this.chartTypeListData,1); 
        }
         if (this.uiComponents.chartTypeMenu[3] != null) {
             this.uiComponents.chartTypeMenu[3].reBind(this.chartTypeMenuData[3], true);
         }
    },
	onChangeTitle:function(t,isAddSymbol,isAuto){
		if(isAuto||!t){
			this._title='Chart';
		}else{
			this._title = t;
		}
		var ticker = '';
		if(typeof this.tickerInfos[this.mainTicker]!='undefined'){
			ticker = this._getClientTicker(this.mainTicker);//this.tickerInfos[this.mainTicker].ticker;
		}
		if (typeof(this.setTitle)=="function") {            
            this.setTitle(this._title,ticker);
        }
    },
	clear:function() {
        this.chartData.DataList = null;
		this.bacthUnscribeTickers([this.mainTicker]);   // unscribe all tikers.
		if(this.compairTickers.length>0)this.bacthUnscribeTickers(this.compairTickers);
		if (typeof(GB_ChartDataManager)=="object") {
			GB_ChartDataManager.unregisterSymbol(this.mainTicker);
			for(var i=0;i<this.compairTickers.length;i++){
				GB_ChartDataManager.unregisterSymbol(this.compairTickers[i]);
			}
			if(typeof(this.id) != "undefined")GB_ChartDataManager.unregisterChart(this.id);
			GB_ChartDataManager.unsubscribeChart(this);
		}
        if (this.sliderObj!=null) {
            this.sliderObj.onchange = null;
            this.sliderObj.onchanged = null;
            this.sliderObj.clear();
        }
        this._contains.pChartContainer.unbind("plothover").unbind("mouseover").unbind("mouseout").unbind("drawEnd").unbind("contextmenu");
        if (this.pFlot != null) {
            this.pFlot.clear();
        }
        if (this.vFlot != null) {
            this.vFlot.clear();
        } 
        if (this.mFlot != null) {
            this.mFlot.clear();
        }
        for(var o in this.iFlots) {
            if(this.iFlots.hasOwnProperty(o) && this.iFlots[o] != null) {
				if(this.iChartContainers[o]!= null)this.iChartContainers[o].find(".lengend").unbind("click").unbind("hover").unbind("contextmenu");
                this.iFlots[o].clear();
            }
        }
		if(typeof(GB_qsAutoCompleteBox)== "object"){
			GB_qsAutoCompleteBox.unSubscription(this.autoBoxID);
		}
        this._contains.pChartContainer.html(""),this._contains.pChartContainer = null;
        if(this._contains.vChartContainer!=null)this._contains.vChartContainer.html(""),this._contains.vChartContainer = null;
        if(this._contains.mChartContainer!=null)this._contains.mChartContainer.html(""),this._contains.mChartContainer = null;
		if(typeof(QSCAL)!="undefined"){ 
			var inputs = this._elements.$customDate.find(".qs-ui-ipt");
			QSCAL.unregister(inputs[0]);
			QSCAL.unregister(inputs[1]);
		} 
		var uComp = this.uiComponents;
		if(uComp.rightMenu != null) uComp.rightMenu.clear();
		if(uComp.miniChartRightMenu){
			for(var o in uComp.miniChartRightMenu){
				if(typeof(uComp.miniChartRightMenu[o].menu.clear)=="function"){
					uComp.miniChartRightMenu[o].menu.clear();
				}
			}
		}
		if(uComp.tabMenu&&typeof(uComp.tabMenu.clear)=="function"){
			uComp.tabMenu.clear();
		}
		if(uComp.funTabMenu&&typeof(uComp.funTabMenu.clear)=="function"){
			uComp.funTabMenu.clear();
		}
		if(uComp.indTabMenu&&typeof(uComp.indTabMenu.clear)=="function"){
			uComp.indTabMenu.clear();
		}
		if(typeof(uComp.customDateB) != "undefined"){
			uComp.customDateB.clear();
		}
		if(uComp.ddlFrequency&&typeof(uComp.ddlFrequency.clear)=="function"){
			uComp.ddlFrequency.clear();
		}
		if(uComp.ddlZoom&&typeof(uComp.ddlZoom.clear)=="function"){
			uComp.ddlZoom.clear();
		}
		if(uComp.ddlChartType&&typeof(uComp.ddlChartType.clear)=="function"){
			uComp.ddlChartType.clear();
		}
		if(uComp.ddlCursorType&&typeof(uComp.ddlCursorType.clear)=="function"){
			uComp.ddlCursorType.clear();
		}
		if(uComp.tabZoomMenu&&typeof(uComp.tabZoomMenu.clear)=="function"){
			uComp.tabZoomMenu.clear();
		}
		if(uComp.chartTypeMenu.length){
			for(var i=0;i<uComp.chartTypeMenu.length;i++){
				if(uComp.chartTypeMenu[i]&& typeof(uComp.chartTypeMenu[i].clear)=="function"){
					uComp.chartTypeMenu[i].clear();
				}
			}
		}
		if(uComp.chkIIV&&typeof(uComp.chkIIV.clear)=="function"){
			uComp.chkIIV.clear();
		}
		if(uComp.chkLock&&typeof(uComp.chkLock.clear)=="function"){
			uComp.chkLock.clear();
		}
		if(this._contains.$settingPanel!=null){
			this._contains.$settingPanel.find(".rtc-menu-trigger").unbind();
		}
		if(uComp.indexScrollPN&&typeof(uComp.indexScrollPN.clear)=="function"){
			uComp.indexScrollPN.clear();
		}
		for(var o in this._elements){
			if(this._elements[o]){
				this._elements[o].unbind();
				this._elements[o] = null;
			}
		}
		if(uComp.settingGroup&&typeof(uComp.settingGroup.clear)=="function"){
			uComp.settingGroup.clear();
		}
		this._contains.$settingPanel.html(""),this._contains.$settingPanel = null;
		for(var p in this){
            if(!p || p == 'clear'){continue;}
            this[p] = null;
            delete this[p];
        }
    },
	storeTickerInfo: function(d,info){
        var tenforInfo = info.TenforeInfo;
        d["tenforeCode"]= tenforInfo!=null&&tenforInfo.length>1?tenforInfo[1]:"";
        d["tenforeTicker"] = tenforInfo!=null&&tenforInfo.length>1?tenforInfo[0]:"";
        d["mType"] = info.Type;
        d["type"] = this._securityTypeMap[info.Type];    // sercurity type
        d["performanceId"] = info.PID;
        d["secId"] = info.SID;
        d["exch"] = info.Exch;
        d["clientTicker"] = info.clientTicker||info.Ticker;
        d["ticker"] = info.Ticker;
        d["country"] = info.Region;
        d["currency"] = info.Currency;
        d["companyId"] = info.CFID;
        d["ISIN"] = info.ISIN;
        d["Name"]= info.Name;
		d["noPID"]= (info.SID==""||info.SID==null)&&(info.PID==""||info.PID==null);
        var eCode = info.Region == "USA"?"126":(tenforInfo!=null?tenforInfo[1]:info.Ticker);
        d["gkey"]= eCode+":"+(tenforInfo!=null?tenforInfo[0]:info.Ticker);
        if(info.Type == "FE"){ // ETF IIV
            if(info.EtfData!=null&&info.EtfData.IIV&&info.EtfData.IIV.TenforeInfo != null){
                var etf = info.EtfData.IIV;
                var pid = info.PID+"IIV";
                var eKey = eCode+":"+etf.TenforeInfo[0];
                this.tickerInfos[pid]={};
                this.tickerInfos[pid]["gkey"] = eKey;
                this.tickerInfos[pid]["tenforeCode"]= eCode;
                this.tickerInfos[pid]["tenforeTicker"] = etf.TenforeInfo[0]
                this.tickerInfos[pid]["type"]= 10;
                this.tickerInfos[pid]["mType"] = "FE";
                this.tickerInfos[pid]["exch"] = etf.Exch;
                this.tickerInfos[pid]["ticker"] = etf.Ticker;
                this.tickerInfos[pid]["clientTicker"] = etf.clientTicker||etf.Ticker;
                this.tickerInfos[pid]["country"] = etf.Region;
                this.tickerInfos[pid]["performanceId"] = pid;
                this.tickerInfos[pid]["secId"] = info.SID;
            }
        }
    }
};
